What is the internal sorting technique used in comparator and comparable interfaces and why? [duplicate]

Both Comparable and Comparator are interfaces. All they do is define a way of asking whether one object is greater than, equal to, or less than another.

The interfaces don’t enforce what that means — that’s up to the class that implements the interface. So one Comparator<Employee> might say that Adam is “greater than” Bill because A comes before B in the alphabet. Another Comparator<Employee> might say that Bill is “greater than” Adam because Bill has been with the company for longer.

Any sort algorithm needs to be able to compare two items, to know which one should come first in the output. If you wrote a bubble sort, you could use Comparator to compare items.

Java has built-in sorts in a few places, including Arrays.sort(), Collections.sort(), Stream::sorted.

The JavaDoc for Arrays and Collections states that:

The implementation was adapted from Tim Peters’s list sort for Python ( TimSort). It uses techiques from Peter McIlroy’s “Optimistic Sorting and Information Theoretic Complexity”, in Proceedings of the Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474, January 1993.

That JavaDoc for Stream does not specify the sort method – I suspect this is because implementations are free to vary.

Leave a Comment