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

前端 未结 5 1204
生来不讨喜
生来不讨喜 2021-02-07 08:07

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 †).

5条回答
  •  情歌与酒
    2021-02-07 08:32

    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.)

提交回复
热议问题