Post on 18-Dec-2015
Quick Sort
2
Quick Sort
• Divide: • Pick any element p as the pivot, e.g, the first element• Partition the remaining elements into
FirstPart, which contains all elements < pSecondPart, which contains all elements ≥ p
• Recursively sort the FirstPart and SecondPart
• Combine: no work is necessary since sorting is done in place
3
Quick Sort
x < p p p ≤ x
PartitionFirstPart SecondPart
ppivot
A:
Recursive call
x < p p p ≤ x
SortedFirstPart
SortedSecondPart
Sorted
4
Quick SortQuick-Sort(A, left, right)if left ≥ right return
else middle ← Partition(A, left,
right) Quick-Sort(A, left, middle–1 ) Quick-Sort(A, middle+1, right)
end if
5
Partitionp
p x < p p ≤ x
p p ≤ xx < p
A:
A:
A:p
6
Partition Example
A: 4 8 6 3 5 1 7 2
7
Partition Example
A: 4 8 6 3 5 1 7 2
i=0
j=1
8
Partition Example
A:
j=1
4 8 6 3 5 1 7 2
i=0
8
9
Partition Example
A: 4 8 6 3 5 1 7 26
i=0
j=2
10
Partition Example
A: 4 8 6 3 5 1 7 2
i=0
383
j=3
i=1
11
Partition Example
A: 4 3 6 8 5 1 7 2
i=1
5
j=4
12
Partition Example
A: 4 3 6 8 5 1 7 2
i=1
1
j=5
13
Partition Example
A: 4 3 6 8 5 1 7 2
i=2
1 6
j=5
14
Partition Example
A: 4 3 8 5 7 2
i=2
1 6 7
j=6
15
Partition Example
A: 4 3 8 5 7 2
i=2
1 6 22 8
i=3
j=7
16
Partition Example
A: 4 3 2 6 7 8
i=3
1 5
j=8
17
Partition Example
A: 4 1 6 7 8
i=3
2 542 3
18
A: 3 6 7 81 542
x < 4 4 ≤ x
pivot incorrect position
Partition Example
19
Partition(A, left, right)1. x ← A[left]2. i ← left3. for j ← left+1 to right4. if A[j] < x then 5. i ← i + 16. swap(A[i], A[j])7. end if8. end for j9. swap(A[i], A[left])10. return in = right – left +1
Time: cn for some constant c Space: constant
20
4 8 6 3 5 1 7 22 3 1 5 6 7 84
Quick-Sort(A, 0, 7)Partition
A:
21
2 3 1
5 6 7 84
2 1 3
Quick-Sort(A, 0, 7)Quick-Sort(A, 0, 2)
A:
, partition
22
2
5 6 7 84
1
1 3
Quick-Sort(A, 0, 7)Quick-Sort(A, 0, 0) , base case, return
23
2
5 6 7 84
1
33
Quick-Sort(A, 0, 7)Quick-Sort(A, 1, 1) , base case
24
5 6 7 842 1 3
2 1 3
Quick-Sort(A, 0, 7)Quick-Sort(A, 2, 2), returnQuick-Sort(A, 0, 2), return
25
42 1 3
5 6 7 86 7 85
Quick-Sort(A, 0, 7)Quick-Sort(A, 2, 2), returnQuick-Sort(A, 4, 7) , partition
26
4
5
6 7 87 866
2 1 3
Quick-Sort(A, 0, 7)Quick-Sort(A, 5, 7) , partition
27
4
5
6
7 887
2 1 3
Quick-Sort(A, 0, 7)Quick-Sort(A, 6, 7) , partition
28
4
5
6
7
2 1 3
Quick-Sort(A, 0, 7)Quick-Sort(A, 7, 7)
8
, return, base case
8
29
4
5
6 87
2 1 3
Quick-Sort(A, 0, 7)Quick-Sort(A, 6, 7) , return
30
4
5
2 1 3
Quick-Sort(A, 0, 7)Quick-Sort(A, 5, 7) , return
6 87
31
42 1 3
Quick-Sort(A, 0, 7)Quick-Sort(A, 4, 7) , return
5 6 87
32
42 1 3
Quick-Sort(A, 0, 7)Quick-Sort(A, 0, 7) , done!
5 6 87