Be Quick To Sort Your Problem Out
Be Quick To Sort Your Problem Out
Divide
Partition an array A[p..r] into two sub-arrays A[p..q-1] and A[q+1..r]
such that elements in subarray A[p..q-1] ≤ A[q] ≤ elements in subarray
A[q+1..r]
The element in A[q] is called the pivot element
Conquer
Sort the two subarrays recursively using Quick Sort
Combine
No work need as in-place sort
Lecture 5 - Quick Sort 11/4/2019
3
Algorithm
Algorithm : QuickSort(A,p,r)
Input : Array, A. Starting index of subarray, p. Ending index of
subarray, q.
Output : A[p..r] in sorted order
Begin
if p < q
then
q ← Partition (A, p, r)
QuickSort(A, p, q-1)
QuickSort(A, q+1, r)
endif
End
p i j r
≤x >x ?
Loop Invariant : At the start of each iteration, for any array index k,
If p ≤ k ≤ i, then A[k] ≤ x. ( x is the pivot element )
If (i + 1) ≤ k ≤ (j – 1), then A[k] > x.
If j ≤ k ≤ (r - 1), A[k] is yet to be compared with x.
If k = r, then A[k] = x.
Lecture 5 - Quick Sort 11/4/2019
6
Complexity
Partition Algorithm?
Θ(n)
Quick Sort Algorithm?
Depends on partitioning the array
If sub-arrays are balanced, it runs as fast as merge sort
If sub-arrays are unbalanced, it runs as slowly as insertion sort
When? 0 1 2 3 4 5 6 7 8 9
Already Sorted
What are the sub-array size after partition?
0 and (n-1) in each iteration
How the recurrence relation will be?
T(n) = T(n-1) + T(0) + Θ(n) = T(n-1) + Θ(n)
Θ(n2)
When? 0 3 2 1 7 5 6 9 8 4