2020-03-11
QuickSort
Input:
Arr
- array to sortleft
- starting indexright
- ending indexUses:
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)
partition
Input:
Arr
- array to partitionleft
- starting indexright
- ending indexPseudocode:
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
QuickSort
Assumptions:
- average number of comparisons used by QuickSort function
Clearly .
Let . After selecting an arbitrary pivot element there are 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 then the right part is of length . Please note that all are equal probability of appearance.
Which gives us following equation for :
However thus we can rewrite the above equation in a more clear way:
This is the Quick Sort Equation.
See this paper by Jacek Cichoń on how to solve this equation.
We get where is the th harmonic number.
We need to obtain an asymptotic of the terms . See this paper by Jacek Cichoń on how to obtain this asymptotic.
We have where is the Euler-Mascheroni constant Above equation can obviously be written as 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: