Quick Sort

by Jerry Sky

2020-03-11



The QuickSort sorting algorithm

Pseudocode QuickSort

Input:

Uses:

Pseudocode:

function QuickSort(Arr, left, right):
  if left < right:
    select a PivotIndex
    pivotNewIndex :=
      partition(Arr, left, right, PivotIndex)

    QuickSort(Arr, left, pivotNewIndex-1)
    QuickSort(Arr, pivotNewIndex+1, right)

Pseudocode partition

Input:

Pseudocode:

function partition(Arr, left, right, PivotIndex):
  pivot = Arr[PivotIndex]

  i := left - 1 // index of smaller element

  for j = left, j <= right - 1, j++:
    if Arr[j] < pivot:
      i++ // increment the index of smaller element
      swap Arr[i] and Arr[j]
  swap Arr[i + 1] and Arr[right]
  return i+1

Resolving the asymptotic of QuickSort

Assumptions:

QnQ_n - average number of comparisons used by QuickSort function

Clearly Q0=Q1=0Q_0 = Q_1 = 0.

Let n≥2n \ge 2. After selecting an arbitrary pivot element there are n−1n-1 comparisons because of the partition function invoked by the QuickSort function. The partition function has divided Arr into two pieces: left and right with the pivot in the middle. Assuming the left part is of length kk then the right part is of length n−1−kn-1-k. Please note that all k∈{0,…,n−1}k \in \{0,\dots,n-1\} are equal probability of appearance.
Which gives us following equation for QnQ_n: Qn=(n−1)+1n∑k=0n−1(Qk+Qn−1−k) Q_n = (n-1) + \frac{1}{n} \sum_{k=0}^{n-1}(Q_k + Q_{n-1-k})

However ∑k=0n−1Qn−1−k=∑k=0n−1Qk\sum_{k=0}^{n-1}Q_{n-1-k} = \sum_{k=0}^{n-1}Q_k thus we can rewrite the above equation in a more clear way: Qn=(n−1)+2n∑k=0n−1Qk Q_n = (n-1) + \frac{2}{n}\sum_{k=0}^{n-1}Q_k

This is the Quick Sort Equation.
See this paper by Jacek Cichoń on how to solve this equation.

We get Qn=(n+1)(4Hn+1−2Hn−4) Q_n = (n+1) (4H_{n+1} - 2H_n -4) where HnH_n is the nnth harmonic number.

We need to obtain an asymptotic of the terms QnQ_n. See this paper by Jacek Cichoń on how to obtain this asymptotic.

We have Qn=2n(ln⁡n+γ−2)+2ln⁡n+2γ+1+O(1n) Q_n = 2n(\ln n + \gamma -2) + 2\ln n + 2\gamma + 1 + O\Big(\frac{1}{n}\Big) where γ\gamma is the Euler-Mascheroni constant Above equation can obviously be written as T(n)=2n(ln⁡n+γ−2)+2ln⁡n+2γ+1+O(1n) T(n) = 2n(\ln n + \gamma -2) + 2\ln n + 2\gamma + 1 + O\Big(\frac{1}{n}\Big) to adhere to the format of previous algorithm analyses we performed.

Above equation describes what is the average time complexity of the QuickSort function.

Sources: