Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort an array of primitives with a custom comparator and without converting to objects

Tags:

java

What's the simplest way to sort a primitive array in Java with a custom comparator (or key) function and without converting to an array of objects (for performance †).

† (Just a precaution, I'm not asking whether not converting to objects is a good decision from a performance POV.)

like image 807
fhucho Avatar asked Mar 26 '14 15:03

fhucho


People also ask

How do you sort a primitive array?

sort() method. Arrays class provides a sort() method for sorting primitive arrays. It sorts the specified array of primitives types into ascending order, according to the natural ordering of its elements. It uses a dual-pivot Quicksort, which is faster than the traditional single-pivot Quicksort.

Can we sort array using Comparator?

To sort an ArrayList using Comparator we need to override the compare() method provided by comparator interface. After rewriting the compare() method we need to call collections.

Is the Comparator code in the arrays sort method called in the same thread as the call to sort or a different thread?

The answer is no.


1 Answers

Sorting of an array of primitive values with a custom comparator is not supported by the standard Java libraries.

You could easily implement your a simple sort ( e.g. bubblesort - O(N^2) ) from scratch, but the problem is that for large enough arrays the saving you make by not converting to boxed types is lost in the less efficient sorting algorithm.

So your choices are:

  • Implement a high performance sort (mergesort, modified quicksort, etc) from scratch.

  • Find an existing high performance sort for primitive types that doesn't support comparators, and modify it.

  • See if you can find a suitable 3rd-party library that supports ptimitive arrays and comparators. (I haven't managed to find one ...)

(Note: the Comparator interface won't work here. It is not suitable for comparing primitive types.)

like image 64
Stephen C Avatar answered Oct 07 '22 11:10

Stephen C