L5 QuickSort Ts
L5 QuickSort Ts
QUICKSORT
Learning outcomes
At the end of this class, you should be able to:
Implement Quicksort algorithm
Determine the running time of Quicksort
COMP 122
In-place and stability
In-place sorting algorithm is one that uses no additional array
storage
A sorting algorithm is stable if duplicate elements remain in the
same relative position after sorting.
QuickSort
Another Divide-and-Conquer sorting algorithm…
As it turns out, MERGESORT and HEAPSORT, although O(n lg n) in
their time complexity, have fairly large constants and tend to move
data around more than desirable (e.g., equal-key items may not
maintain their relative position from input to output).
We introduce another algorithm with better constants, but a flaw: its
worst case in O(n2). Fortunately, the worst case is “rare enough” so
that the speed advantages work an overwhelming amount of the
time… and it is O(n lg n) on average.
Introduction
Like in MERGESORT, we use Divide-and-Conquer:
1.Divide: partition A[p..r] into two subarrays A[p..q-1] and A[q+1..r] such
that each element of A[p..q-1] is ≤ A[q], and each element of A[q+1..r] is ≥
A[q]. Compute q as part of this partitioning.
2.Conquer: sort the subarrays A[p..q-1] and A[q+1..r] by recursive calls to
QUICKSORT.
3.Combine: the partitioning and recursive sorting leave us with a sorted
A[p..r] – no work needed here.
An obvious difference is that we do most of the work in the divide stage,
with no work at the combine one.
QuickSort
The Pseudo-Code
Partition
Proof of Correctness: PARTITION
We look for a loop invariant and we observe that at the
beginning of each iteration of the loop (line 3-6) for any
array index k:
◦ 2. A[j] ≤ x.
The Invariant
Termination. j=r. Every entry in the array is in one of the three sets described by the
invariant. We have partitioned the values in the array into three sets: less than or equal
to x, greater than x, and a singleton containing x.