I'm trying to figure out how to do a multilevel sort of a 2D array of integers in java, where the first numbers takes priority.
so a dataset like this:-
{1,2}
{2,9}
{2,7}
{2,8}
{5,6}
{5,8}
{5,2}
{4,1}
{4,4}
Should return something like this:-
{1,2}
{2,7}
{2,8}
{2,9}
{4,1}
{4,4}
{5,2}
{5,6}
{5,8}
How about this:
for(int i = 0; i < arr.length; i++)
{
int min = i;
for(int j = i; j < arr.length; j++)
{
if(arr[min][0] > arr[j][0])
{
min = j;
}
}
int[] temp = arr[min];
arr[min] = arr[i];
arr[i] = temp;
}
for(int i = 0; i < arr.length; i++)
{
int min = i;
for(int j = i; j < arr.length; j++)
{
if(arr[j][0] != arr[i][0])
break;
if(arr[min][1] > arr[j][1])
min = j;
}
int[] temp = arr[min];
arr[min] = arr[i];
arr[i] = temp;
}
Here's a way to do it:
import java.util.*;
public class Test
{
public static void main(String []args)
{
Integer[][] a = {
{1,2},
{2,9},
{2,7},
{2,8},
{5,6},
{5,8},
{5,2},
{4,1},
{4,4}
};
Arrays.sort(a, new Comparator<Integer[]>()
{
public int compare(Integer[] a, Integer[] b)
{
int res = a[0].compareTo(b[0]);
if(res!=0)
return res;
return a[1].compareTo(b[1]);
}
});
System.out.println(Arrays.deepToString(a));
}
}
Here's a solution using Comparator.class
int[][] array = {{1,2},{2,9}, {2,7},{2,8},{5,6},{5,8},{5,2},{4,1}, {4,4}};
Arrays.sort(array, new Comparator<int[]>() {
@Override
public int compare(int[] o1, int[] o2) {
if(o1[0] == o2[0]){
return o1[1]-o2[1];
}else {
return o1[0]-o2[0];
}
}
});
System.out.println(Arrays.deepToString(array));
Prints this : [[1, 2], [2, 7], [2, 8], [2, 9], [4, 1], [4, 4], [5, 2], [5, 6], [5, 8]]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.