Professional Documents
Culture Documents
3 Quick Sort
3 Quick Sort
Quick sort
Lecture 5
References:
Introduction to Algorithms, Thomas H. Cormen, 2ed edition,
PARTITION (A, p, r)
1. x ← A [r]
2. i ← p – 1
3. for j ← p to r – 1
4. do if A[ j] ≤ x
5. then i ← i + 1
6. exchange A [i] ↔ A [j]
7. exchange A [i + 1] ↔ A [r]
8. return i + 1
Figure below shows the operation of
PARTITION on an 8-element array.
PARTITION always selects an element x = A
[r] as a pivot element around which to partition
the sub array A[p…...r].
Partitioning the array
i p, j r
(a) 2 8 7 1 3 5 6 4
p, i j r
(b) 2 8 7 1 3 5 6 4
p. i j r
(c) 2 8 7 1 3 5 6 4
p, i j r
(d) 2 8 7 1 3 5 6 4
p i j r
(e) 2 1 7 8 3 5 6 4
p i j r
(f) 2 1 3 8 7 5 6 4
p i j r
(g) 2 1 3 8 7 5 6 4
p i j r
(h) 2 1 3 8 7 5 6 4
p i r
(i) 2 1 3 4 7 5 6 8