Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What sort does Java Collections.sort(nodes) use?

I think it is MergeSort, which is O(n log n).

However, the following output disagrees:

-1,0000000099000391,0000000099000427
1,0000000099000427,0000000099000346
5,0000000099000391,0000000099000346
1,0000000099000427,0000000099000345
5,0000000099000391,0000000099000345
1,0000000099000346,0000000099000345

I am sorting a nodelist of 4 nodes by sequence number, and the sort is doing 6 comparisons. I am puzzled because 6 > (4 log(4)). Can someone explain this to me?

P.S. It is mergesort, but I still don't understand my results.

Thanks for the answers everyone. Thank you Tom for correcting my math.

like image 764
Kyle Jones Avatar asked Apr 15 '09 19:04

Kyle Jones


People also ask

Which sorting algorithm is used while sorting a collection in Java using collections sort method *?

sort method and Collection. sort() uses Timsort. Which order of sorting is done by default?

Does collections sort sort ascending or descending?

By default, Collection. sort performs the sorting in ascending order. If we want to sort the elements in reverse order we could use following methods: reverseOrder() : Returns a Comparator that imposes the reverse of natural ordering of elements of the collection.

Which sort does sort () use?

Algorithm used by sorted() The Python sorted() uses the Timsort algorithm which is a hybrid sorting algorithm, derived from merge sort and insertion sort.

Does collections sort use Compareto?

Collections class has a second sort() method and it takes Comparator. The sort() method invokes the compare() to sort objects.


2 Answers

O(n log n) doesn't mean that the number of comparisons will be equal to or less than n log n, just that the time taken will scale proportionally to n log n. Try doing tests with 8 nodes, or 16 nodes, or 32 nodes, and checking out the timing.

like image 153
Andy Mikula Avatar answered Sep 28 '22 05:09

Andy Mikula


You sorted four nodes, so you didn't get merge sort; sort switched to insertion sort.

In Java, the Arrays.sort() methods use merge sort or a tuned quicksort depending on the datatypes and for implementation efficiency switch to insertion sort when fewer than seven array elements are being sorted. (Wikipedia, emphasis added)

Arrays.sort is used indirectly by the Collections classes.

A recently accepted bug report indicates that the Sun implementation of Java will use Python's timsort in the future: http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6804124

(The timsort monograph, linked above, is well worth reading.)

like image 21
tpdi Avatar answered Sep 28 '22 05:09

tpdi