Reputation: 2085
For example:
My first column in the array is at first numerically in order. The Second column is numerically random. I want to place the second column in order, which of course will force the first column out of order. Any ideas how to do this in java. I have searched, but can't seem to find the vocabulary to properly find it.
Upvotes: 1
Views: 6449
Reputation: 18633
The method you can use is one of the Arrays.sort(), where you define your own comparator, which can compare two rows of a two-dimensional array.
The code below allocates an array with two columns and ten rows, with the first column sorted and the second one completely random. Then it sorts it according to the second column.
class Test{
static void print(int[][] a){
for (int i=0;i<a.length;i++){
for (int j=0;j<a[0].length;j++)
System.out.print(a[i][j]+" ");
System.out.println();
}
}
public static void main(String[]args){
java.util.Random r = new java.util.Random();
int[][] a = new int[10][2];
for (int i=0;i<a.length;i++){
a[i][0]=i+1;
a[i][1]=r.nextInt(100);
}
print(a);
System.out.println();
java.util.Arrays.sort(a,
new java.util.Comparator<int[]>(){
public int compare(int[]a,int[]b){
return a[1]-b[1];
}
});
print(a);
}
}
Example output:
1 8
2 49
3 82
4 89
5 8
6 0
7 83
8 89
9 8
10 46
6 0
1 8
5 8
9 8
10 46
2 49
3 82
7 83
4 89
8 89
Upvotes: 5