Sort multidimensional array based on the difference in the value, if the value is the same; sort on the first column.
Java Solution needed.
If not code, I would like to know the approach or any kind of hint to solve this type of problem.
Constrains : No of rows can be any but fixed no of column ie 2.
Example:
int arr[][] = new int[5][2]
[0] [1]
[0] 0 6
[1] 0 7
[2] 4 5
[3] 2 3
[4] 0 1
Final Output:
[0] [1]
[0] 0 1
[1] 2 3
[2] 4 5
[3] 0 6
[4] 0 7
Explanation:
difference between: arr[0][1] - arr[0][0] -> 6-0 -> 6
difference between: arr[1][1] - arr[1][0] -> 7-0 -> 7
difference between: arr[2][1] - arr[2][0] -> 5-4 -> 1 — same length ie 1
difference between: arr[3][1] - arr[3][0] -> 3-2 -> 1 — same length ie 1
difference between: arr[4][1] - arr[4[0] -> 1-0 -> 1 — same length ie 1
I want to sort on the difference, in cases where difference is same I want to sort those with same difference on column [0]
So in this case,
The below 3 have same difference
difference between: arr[2][1] - arr[2][0] -> 5-4 -> 1 — same difference ie 1
difference between: arr[3][1] - arr[3][0] -> 3-2 -> 1 — same difference ie 1
difference between: arr[4][1] - arr[4[0] -> 1-0 -> 1 — same difference ie 1
Need to sort the above 3 based on there column[0] value
arr[2][1] - arr[2][0] -> 5-4 -> 1 — value here is 4 ie arr[2][0]
arr[3][1] - arr[3][0] -> 3-2 -> 1 — value here is 2 ie arr[3][0]
arr[4][1] - arr[4[0] -> 1-0 -> 1 — value here is 1 ie arr[4][0]
So the the one with the least value in column[0] should be first,
In final output,
arr[4][1] - arr[4[0] -> 1-0 -> 1 ——> 1st
arr[3][1] - arr[3][0] -> 3-2 -> 1 ——> 2nd
arr[4][1] - arr[4[0] -> 1-0 -> 1 ——> 3rd
arr[0][1] - arr[0][0] -> 6-0 -> 6 ——> 4th
arr[1][1] - arr[1][0] -> 7-0 -> 7 ——> 5th
Edit 1: Help needed in determining the Time complexity? Thanks for all the suggestion and code. Below is my version of working code: I would like to know the time complexity of my code? In short, what is the complexity of sorting a 2d array. 1d array --> O(n.logn) 2d --> ??
private static int solve(int pathLength, int[][] floristIntervals) {
// TODO Auto-generated method stub
System.out.println(Arrays.deepToString(floristIntervals));
Arrays.sort(floristIntervals, new Comparator<int[]>(){
@Override
public int compare(int[] o1, int[] o2) {
// TODO Auto-generated method stub
/*System.out.println(o1[0]);
System.out.println(o1[1]);
System.out.println(o2[0]);
System.out.println(o2[1]);*/
if(o2[1]-o2[0] == o1[1]-o1[0]){
if(o2[0] > o1[0]){
return -1;
}
return 1;
}
if (o2[1]-o2[0] > o1[1]-o1[0])
return 1;
else
return -1;
}
});
System.out.println(Arrays.deepToString(floristIntervals));