Skip to content
Advertisement

Java – Collections.sort() performance

I’m using Collections.sort() to sort a LinkedList whose elements implements Comparable interface, so they are sorted in a natural order. In the javadoc documentation its said this method uses mergesort algorithm which has n*log(n) performance.

My question is if there is a more efficient algorithm to sort my LinkedList?

The size of that list could be very high and sort will be also very frequent.

Advertisement

Answer

O(N log N) is very good asymptotically. That said, there are linear time O(N) non-comparison based sort, e.g. counting sort and bucket sort. This is useful when, e.g. you’re sorting millions and millions of integers, but they’re between 1..10.

Also, if the list is “almost sorted”, the otherwise quadratic insertion sort is reported to actually be better under some scenarios.

Whether or not this is applicable, or even worth to implement, depends on your profiling results. I’d say that unless it shows the sort to be a bottleneck, don’t worry about it.

See also

Related questions

Advertisement