Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort an array of ints using a custom comparator?

Tags:

java

sorting

I need to sort an array of ints using a custom comparator, but Java's library doesn't provide a sort function for ints with comparators (comparators can be used only with objects). Is there any easy way to do this?

like image 601
Alexandru Avatar asked Sep 13 '10 09:09

Alexandru


People also ask

How do you sort an array using Comparator?

int[][] twoDim = { { 1, 2 }, { 3, 7 }, { 8, 9 }, { 4, 2 }, { 5, 3 } }; Arrays. sort(twoDim, (int[] o1, int[] o2) -> o2[0] - o1[0]); System. out. println(Arrays.

Which method is used to sort using Comparator?

Using a comparator, we can sort the elements based on data members. For instance, it may be on roll no, name, age, or anything else. Method of Collections class for sorting List elements is used to sort the elements of List by the given comparator.


1 Answers

If you can't change the type of your input array the following will work:

final int[] data = new int[] { 5, 4, 2, 1, 3 }; final Integer[] sorted = ArrayUtils.toObject(data); Arrays.sort(sorted, new Comparator<Integer>() {     public int compare(Integer o1, Integer o2) {         // Intentional: Reverse order for this demo         return o2.compareTo(o1);     } }); System.arraycopy(ArrayUtils.toPrimitive(sorted), 0, data, 0, sorted.length); 

This uses ArrayUtils from the commons-lang project to easily convert between int[] and Integer[], creates a copy of the array, does the sort, and then copies the sorted data over the original.

like image 119
Jon Freedman Avatar answered Sep 17 '22 22:09

Jon Freedman