Reverse sorting an int array in java. Help please.

tpfaff

2[H]4U
Joined
Jan 30, 2006
Messages
2,526
public void Descending(int array[]) {
Arrays.sort(array, Collections.reverseOrder());
System.out.println(Arrays.toString(array));
}

Getting an error at the red word, It says can not find symbol

symbol:method sort(int[] , java.util.Comparotor<java.lang.Object>
location: class java.util.Arrays
 
Is that your complete code? Tried compiling the file with the -verbose switch?

Not sure if I remember correctly, but I don't believe theres a method that sorts an int array with a Comparator. You might need to use an object array of ints to do that.. but that's hard to say without the complete code.

On second thought, you could sort it first, then reverse it, but that doesn't fix (what I think is) the fundamental flaw here.
 
No it's not the complete code. As for the verbose switch, I dont even know what that means!
I'm trying to convert the array to a string list and then sort it reverse order but it keeps crashing too =/
 
alright how about this bad boy


public void Descending(int array[]) {
String[] strArray = new String[array.length];
for (int i = 0; i < array.length; i++) {
strArray = Integer.toString(array);
Arrays.sort(strArray);
Arrays.sort(strArray, Collections.reverseOrder());


for (int a = 0; a < array.length; a++) {
array[a] = Integer.parseInt(strArray[a]);
}
for (int a : array) {
System.out.println(a);
}
System.out.println(Arrays.toString(array));

}

}

produces no errors but crashes when run
 
you dont want to sort an int array as strings. You need the numerical ordering, not the character ordering (10 is more than 2, not less than).

Additionally, int is a primitive, and the method you are trying to use is T[], which is for use on objects.

sort(T[] a, Comparator<? super T> c)

You could turn your int[] into a Integer[]. Integer is an class with instances as objects, not as primitive. You could use your comparator then.

Or you could use the plain Arrays.sort(int[]) to avoid the int[] -> Integer[] and back conversion, and manually reverse the output, its not difficult - just be sure to check your results with an even length & odd length input array.

Thats reverse numerical order, not the reverse order of the input.
 
Last edited:
Back
Top