$ \def\compare{ {\mathrm{compare}} } \def\swap{ {\mathrm{swap}} } \def\sort{ {\mathrm{sort}} } \def\insert{ {\mathrm{insert}} } \def\true{ {\mathrm{true}} } \def\false{ {\mathrm{false}} } \def\BubbleSort{ {\mathrm{BubbleSort}} } \def\SelectionSort{ {\mathrm{SelectionSort}} } \def\Merge{ {\mathrm{Merge}} } \def\MergeSort{ {\mathrm{MergeSort}} } \def\QuickSort{ {\mathrm{QuickSort}} } \def\Split{ {\mathrm{Split}} } $
SelectionSort. $O(n^2)$ operations
BubbleSort and InsertionSort. $O(n^2)$ operations
MergeSort. $O(n \log n)$ operations
QuickSort: Divide by Value
Idea. Divide array $a$ by value
QuickSort(a, i, j):
if j - i <= 1 then
return
endif
p <- GetPivot(a, i, j) # select a pivot
k <- Split(a, i, j, p)
QuickSort(a, i, k-1)
QuickSort(a, k+1, j)
Split(a, i, j, p):
left <- i, right <- j
while left < right do
if a[left] > p and a[right] <= p then
swap(a, left, right)
left++, right--
else
if a[left] <= p then left++
if a[right] > p then right--
endif
endwhile
return right
QuickSort(a, i, j):
if j - i <= 1 then
return
endif
p <- GetPivot(a, i, j) # select a pivot
k <- Split(a, i, j, p)
QuickSort(a, i, k-1)
QuickSort(a, k+1, j)
Assume $\mathrm{GetPivot}(a, i, j)$ returns a value in $a[i..j]$
Best pivot selection?
What if we can’t get the best possible? What might still be acceptable?
A pivot $p$ is good if its rank is between $\frac 1 4 k$ and $\frac 3 4 k$
Question. How many good pivots until we reach a base case?
GetPivot(a, i, j):
k <- RandomInt(i, j)
return a[k]
Question. How likely is it that a pivot is good?
With random pivot selection
So running time is $O(n \log n)$ on average
Can show. If random pivot is chosen, then on average QuickSort uses $O(n \log n)$ operations
Formalizing previous argument is a bit tricky
More clever and simpler analyses exist!
Homework 2!
Lower bounds for sorting
Lecture Ticket: Argue that every sorting algorithm uses $\Omega(n)$ operations