Sort int array in descending order

Possible duplicate:
Sort arrays of primitive types in descending order
Java: how to sort an array of floats in reverse order?
How to change int array in Java?

The following code sorts the array in ascending order:

int a[] = {30,7,9,20}; Arrays.sort(a); System.out.println(Arrays.toString(a)); 

I need to sort it in descending order. How to use Comparator for this?

Please, help.

+25
source share
4 answers

For primitive array types, you will have to write a reverse sort algorithm:

Alternatively, you can convert int[] to Integer[] and write a comparator:

 public class IntegerComparator implements Comparator<Integer> { @Override public int compare(Integer o1, Integer o2) { return o2.compareTo(o1); } } 

or use Collections.reverseOrder() as it only works with non-primitive array types.

and finally

 Integer[] a2 = convertPrimitiveArrayToBoxableTypeArray(a1); Arrays.sort(a2, new IntegerComparator()); // OR // Arrays.sort(a2, Collections.reverseOrder()); //Unbox the array to primitive type a1 = convertBoxableTypeArrayToPrimitiveTypeArray(a2); 
+17
source

Guava has an Ints.asList() method to create a List<Integer> supported by an int[] array. You can use this with Collections.sort to apply a comparator to the underlying array.

 List<Integer> integersList = Ints.asList(arr); Collections.sort(integersList, Collections.reverseOrder()); 

Note that the latter is a live list maintained by the actual array, so it should be quite efficient.

+5
source
  Comparator<Integer> comparator = new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o2.compareTo(o1); } }; // option 1 Integer[] array = new Integer[] { 1, 24, 4, 4, 345 }; Arrays.sort(array, comparator); // option 2 int[] array2 = new int[] { 1, 24, 4, 4, 345 }; List<Integer>list = Ints.asList(array2); Collections.sort(list, comparator); array2 = Ints.toArray(list); 
+5
source

If it's not a large / long array, just flip it:

 for( int i = 0; i < arr.length/2; ++i ) { temp = arr[i]; arr[i] = arr[arr.length - i - 1]; arr[arr.length - i - 1] = temp; } 
+4
source

All Articles