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

Quick sort Worst case

Quicksort’s performance is dependent on your pivot selection algorithm. The most naive pivot selection algorithm is to just choose the first element as your pivot. It’s easy to see that this results in worst case behavior if your data is already sorted (the first element will always be the min). There are two common algorithms … Read more

Multithreaded quicksort or mergesort

give a try to fork/join framework by Doug Lea: public class MergeSort extends RecursiveAction { final int[] numbers; final int startPos, endPos; final int[] result; private void merge(MergeSort left, MergeSort right) { int i=0, leftPos=0, rightPos=0, leftSize = left.size(), rightSize = right.size(); while (leftPos < leftSize && rightPos < rightSize) result[i++] = (left.result[leftPos] <= right.result[rightPos]) … Read more

Quicksort: Choosing the pivot

Choosing a random pivot minimizes the chance that you will encounter worst-case O(n2) performance (always choosing first or last would cause worst-case performance for nearly-sorted or nearly-reverse-sorted data). Choosing the middle element would also be acceptable in the majority of cases. Also, if you are implementing this yourself, there are versions of the algorithm that … Read more

Quicksort with Python

def sort(array=[12,4,5,6,7,3,1,15]): “””Sort the array by using quicksort.””” less = [] equal = [] greater = [] if len(array) > 1: pivot = array[0] for x in array: if x < pivot: less.append(x) elif x == pivot: equal.append(x) elif x > pivot: greater.append(x) # Don’t forget to return something! return sort(less)+equal+sort(greater) # Just use the … Read more