Why does Java’s Arrays.sort method use two different sorting algorithms for different types?

The most likely reason: quicksort is not stable, i.e. equal entries can change their relative position during the sort; among other things, this means that if you sort an already sorted array, it may not stay unchanged. Since primitive types have no identity (there is no way to distinguish two ints with the same value), … Read more

How to sort in-place using the merge sort algorithm?

Knuth left this as an exercise (Vol 3, 5.2.5). There do exist in-place merge sorts. They must be implemented carefully. First, naive in-place merge such as described here isn’t the right solution. It downgrades the performance to O(N2). The idea is to sort part of the array while using the rest as working area for … Read more

Why is quicksort better than mergesort?

Quicksort has O(n2) worst-case runtime and O(nlogn) average case runtime. However, it’s superior to merge sort in many scenarios because many factors influence an algorithm’s runtime, and, when taking them all together, quicksort wins out. In particular, the often-quoted runtime of sorting algorithms refers to the number of comparisons or the number of swaps necessary … Read more