Skip to content

Quick Sort

Implementation

Partitioning

There are 2 main algorithms that does 2-way partitioning, namely:

Additionally, you can look at Dutch Flag Algorithm for an algorithm that partitions 3-way.

Sorting

Being a recursive algorithm, by constantly partitioning each half, we'll get a sorted array.

Time Complexity

  • Time Complexity (Expected): \(O(n \log n)\)
  • Time Complexity (Worst): \(O(n^{2})\)

Space Complexity

Even though quick sort is in-place, does it take up \(O(1)\) extra space?

Recursion takes up space. Even though each stack frame takes up \(O(1)\) space, but how many frames are there?

  • Space Complexity (Expected): \(O(\log n)\)
  • Space Complexity (Worst): \(O(n)\)

Quick Select

A modification to the quick sort algorithm to do solve other problems. This algorithm is primarily used to select the \(k\)-th largest item in expected \(O(n)\) time.

How the algorithm works

  1. After performing the partition step, we know the rank of the pivot.

    • As we can see the example below, after partitioning the array using 3 as the pivot. It is now in the correct place (3rd place).

  2. Once we know the rank of the pivot, we can then decide whether to recurse on the right half or left half, depending on whether \(k\) is larger or smaller than the rank of the pivot.

Time Complexity

In the expected case, we hope to half the search space every time. In each recursive step, we need linear time to do the partitioning. The recursive formula will be:

\[ T(n) = T\left( \frac{n}{2} \right) + O(n) = O(n) \]

Info

For purist who don't want to abuse the master theorem, you can see the time taken will be:

\[ T(n) = \underbrace{ n + \frac{n}{2} + \frac{n}{4} + \dots }_ { \log n \text{ times} } \leq \underbrace{ n + \frac{n}{2} + \frac{n}{4} + \dots }_ { \infty \text{ times} } = 2n \in O(n) \]

In the worst case, we only reduce the search space by one element. We'll have:

\[ T(n) = T(n-1) + O(n) = O(n^{2}) \]
  • Time Complexity (Expected): \(O(n)\)
  • Time Complexity (Worst): \(O(n^{2})\)