view raw
Ad Infinitum Ad Infinitum - 9 months ago 57
Java Question

Which algorithm use sorted method in Stream interface

When I print the values in the sorted method,

Stream.of("d", "a", "b", "e", "c", "f")
.sorted((s1, s2) -> {
System.out.printf("sort: %s - %s\n", s1, s2);
return s1.compareTo(s2);

The output is as follows;

sort: a - d
sort: b - a
sort: b - d
sort: b - a
sort: e - b
sort: e - d
sort: c - d
sort: c - b
sort: f - c
sort: f - e

I could not understand the logic of the sorting algorithm here. Any help will be appreciated.

Edit: The downvoters, please vote down with a reason, which helps me figure out what is wrong with the question.


After running it through debugger using OpenJDK 8, unsurprisingly, it turned out to be Timsort. It's basically a merge sort which uses insertion sort when the divisions of the input are small enough (32 or fewer elements with my version).

If you are interested in how it works in detail, refer to OpenJDK 8 Arrays::sort, for example on grepcode: