QUICKSORT(A, p, r )
if p < r
then q ←PARTITION(A, p, r )
QUICKSORT(A, p, q − 1)
QUICKSORT(A, q + 1, r )
Initial call is QUICKSORT(A, 1, n).
Partitioning
Partition subarray A[p . . r ] by the following procedure:
PARTITION(A, p, r )
x ← A[r ]
i ← p − 1
for j ← p to r − 1
do if A[ j ] ≤ x
then i ← i + 1
exchange A[i ] ↔ A[ j ]
exchange A[i + 1] ↔ A[r ]
return i + 1
• PARTITION always selects the last element A[r ] in the subarray A[p . . r ] as the
pivotthe element around which to partition.
• As the procedure executes, the array is partitioned into four regions, some of
which may be empty:
Loop invariant:
1. All entries in A[p . . i ] are ≤ pivot.
2. All entries in A[i + 1 . . j − 1] are > pivot.
3. A[r ] = pivot.
Its not needed as part of the loop invariant, but the fourth region is A[ j . . r−1],
whose entries have not yet been examined, and so we dont know how they
compare to the pivot.
快速排序详解
651

被折叠的 条评论
为什么被折叠?



