Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting int array in descending order [duplicate]

Possible Duplicate:
Sort arrays of primitive types in descending order
Java : How to sort an array of floats in reverse order?
How do I reverse an int array in Java?

The following code will sort 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 do I use Comparator to do this?

Please help.

like image 582
android Avatar asked Sep 14 '11 09:09

android


People also ask

How do I sort an int array in descending order?

To sort an array in Java in descending order, you have to use the reverseOrder() method from the Collections class. The reverseOrder() method does not parse the array. Instead, it will merely reverse the natural ordering of the array.

Which sorting algorithm is best for duplicates?

A simple solution would be to use efficient sorting algorithms like Merge Sort, Quicksort, Heapsort, etc., that can solve this problem in O(n. log(n)) time, but those will not take advantage of the fact that there are many duplicated values in the array. A better approach is to use a counting sort.

How do you sort a primitive array in descending order?

It's not possible to sort an array of primitives in “descending” order using the Arrays. sort() and Collections. sort() method, since the comparator work on the Wrapper classes and objects instead of the primitives. For instance, the following code reverse sort an Integer array using the Arrays.


1 Answers

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

Alternatively, you can convert your 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() since it only works on 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); 
like image 130
Buhake Sindi Avatar answered Oct 12 '22 07:10

Buhake Sindi