With my following code I try to sort a two dimensional array
int[][] d2 = {
{4,5,1},
{4,1,1},
{1,7,1},
{3,3,2},
{1}
};
java.util.Arrays.sort(d2, new java.util.Comparator<int[]>() {
public int compare(int[] a, int[] b) {
return a[0] - b[0];
}
});
I display the array after sorting
for (int r=0; r<d2.length; r++) {
for (int c=0; c<d2[r].length; c++) {
System.out.print(" " + d2[r][c]);
}
System.out.println("");
}
The Result I get is like this
1 7 1
1
3 3 2
4 5 1
4 1 1
I want the result two come like this
1
1 7 1
3 3 2
4 5 1
4 1 1
What is required to be done to get the array sorted like the above?
I tried replacing the {1}
with {1,0,0}
but it still gives the same result even for {1,0,1}
.
Compare the length of passed array in the compare
method.. If length of a[]
is less than b[]
, return -1: -
java.util.Arrays.sort(d2, new java.util.Comparator<int[]>() {
public int compare(int[] a, int[] b) {
if (a.length != b.length) {
return a.length < b.length ? -1 : 1;
}
return a[0] - b[0];
}
});
If you want to sort, by checking each element, which I think you should do this way.. Change your compare
method to: -
public int compare(int[] a, int[] b) {
if (a.length == b.length) {
for (int i = 0; i < a.length; i++) {
if (a[i] == b[i]) {
} else {
return a[i] - b[i];
}
}
return 0;
} else {
return a.length < b.length ? -1 : 1;
}
}
In your Comperator
you only use the first field to compare 2 arrays. You have to include all the fields to compare them or at least you have to check the length of the arrays to get your desired result.
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.