Quicksort is fast, really fast. Prof Emara calls it a legendary sorting algorithm. It uses a divide-and-conquer approach — for some array and some index , if all the elements to the left of are less than , and all elements to the right are greater than , then we know that arr[x]
is in the correct position. We call this index a pivot.
It has a time complexity of and .
To generalise, we have two steps:
- Partition: function takes in some array, a low and high position, then returns the index of the pivot.
- Do the sorting.
We can take the first element as the pivot. Then, we set some left and right indices of the array to sort within. We increment left
by one index to look for arr[left] > pivot
. We decrement right
to look for arr[right] < pivot
. We can then quicksort the left and right sub-arrays until one recursive layer of QS has low > high
.
Here is a recursive implementation of quicksort in C: