Quicksort algorithm#
Like Merge Sort, QuickSort is a Divide and Conquer algorithm, but it works a bit differently.
Quicksort starts by selecting a pivot element from the array and partitioning the other elements into two sub-arrays, according to whether they are less than or greater than the pivot. The sub-arrays are then sorted recursively.
Quicksort algorithm doesn’t use any extra space, as the sorting is done in-place.
There are several ways that this algorithm can choose a pivot element.
- Pick first element as pivot
- Pick last element as pivot
- Pick a random element as pivot
- Pick median as pivot
Implementation in JavaScript#
The key process below is our partition function, which chooses our pivot. In this implementation, this is done using the Hoare Partition scheme, which works by initializing two indices that start at the ends of the array. The indices move toward each other until an inversion is found.
An inversion is a pair of elements, one greater than or equal to the pivot, one less than or equal, that are in the wrong order relative to each other. The inverted values are then swapped and the process is repeated.
Picking a good pivot is the key for a fast implementation of Quicksort. In practice, Quicksort algorithms use a randomized pivot, which has an expected time complexity of O(nlogn).