Quicksort
Quicksort and merge sort are both in-place and
divide-and-conquer recursive algorithms.
Quicksort Sorting A[p ... r]
-
Divide:: A[p ... r] into A[p ... q] and A[q+1 ... r]
all have q determined as a part of the divide.
-
Conquer:: A[p ... q] and A[q+1 ... r] are sorted
recursively
-
Combine:: None as all this leaves sorted array in
place
Quicksort ( A, p, r )
-
if p < r
-
then q ¬
Paritition ( A, p, r )
-
Quicksort ( A, p, q )
-
Quicksort ( A, q+1, r )
To sort an entire array A, the initial call is Quicksort (
A, 1, length[A] )
Partitioning the array
The key to the algorithm is the Partition procedure which
rearranges the sub array A[p ...r] in place.
Partition ( A, p, r )
-
x ¬ A[p]
-
i ¬ p -1
-
j ¬ r + 1
-
while True
-
do repeat j ¬
j - 1
-
until A[j] £ x
-
repeat i ¬
i + 1
-
until A[i] ³ x
-
If i < j
-
then exchange A[i] « A[j]
-
else return j
The cost of the Partition algorithm is Q
(n)
The operation of Partition on a sample array. The colored cells are not yet
in order. |