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.)
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.
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.
The answer is no.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With