CS146
Chris Pollett
Mar 3, 2014
QUICKSORT(A, p, r) 1 if p < r 2 q = PARTITION(A, p, r) 3 QUICKSORT(A, p, q - 1) 4 QUICKSORT(A, q + 1, r)
Let's look at a first way we might go about implementing the partition procedure which rearranges the subarray `A[p..r]` in place:
PARTITION(A, p, r) 1 x = A[r] 2 i = p - 1 3 for j = p to r - 1 4 if A[j] <= x 5 i = i + 1 6 exchange A[i] with A[j] 7 exchange A[i+1] with A[r] 8 return i + 1
Theorem. The partition function for quicksort satisfies the following loop invariant:
At the beginning of each iteration of the loop of lines 3-6, for any array index `k`
- If `p le k le i`, then `A[k] le x`
- If `i+1 le k le j-1` then `A[k] > x`
- If `k=r`, then `A[k] = x`
Proof. We need to show the three properties of loop invarants:
In the termination setting, the exchange in line 7 puts `x` into the correct place in the partitioned array and the return statement gives the position of the partition in the array so it can be used by quicksort.
Since partition involves only a single loop and otherwise statements each involving constant work, its run time will be `Theta(n)`, where `n = r - p +1`.
Which of the following statements is true?
Which of the following statements is true?