Sort multidimensional array based of the difference in the value, if value is same sort on first column
Sort multidimensional array based of the difference in the value, if value is same sort on first column.
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
Sandesh Wani
- 13
- 3
lang-java