Quicksort

Quicksort is an $$O(n \log n)$$ sort and a randomized algorithm. its worst case is $$O(n^2)$$. it is not stable, and not adaptive.

= Explanation =

The partition
A Partition is a function that takes an array, chooses an element called the "pivot", and arranges the array in such a way that every element smaller than the pivot is to the front of it and every element larger than the pivot is to the back of it.

The sort
To Quicksort an array, first partition it, then Quicksort left and right of the pivot recursively.

= Example = Take the array {7 12 6 11 3 15 1 14 2 16 8 10 9 13 5 4}.

first, partition it (arbitrarily choosing the lowest element as the pivot):

{6 3 1 2 5 4} {7} {12 11 15 14 16 8 10 9 13}

sort the left half:

{3 1 2 5 4} {6} {7} {12 11 15 14 16 8 10 9 13}

{1 2} {3} {5 4} {6} {7} {12 11 15 14 16 8 10 9 13}

{1} {2} {3} {4} {5} {6} {7} {12 11 15 14 16 8 10 9 13}

Append:

{1 2 3 4 5 6} {7} {12 11 15 14 16 8 10 9 13}

Sort the right half:

{1 2 3 4 5 6} {7} {11 8 10 9} {12} {16 14 15 13}

{1 2 3 4 5 6} {7} {8 10 9} {11} {12} {16 14 15 13}

{1 2 3 4 5 6} {7} {8} {10} {9} {11} {12} {16 14 15 13}

{1 2 3 4 5 6} {7} {8} {10} {9} {11} {12} {13} {14} {15} {16}

Append: {1 2 3 4 5 6 7 8 10 9 11 12 13 14 15 16}

Sorted!