Quick Sort
Quick Sort
STRUCTURES
MAHESH GOYANI
MAHATMA GANDHI INSTITUE OF TECHNICAL EDUCATION & RESEARCH CENTER
[email protected]
x<p p p≤x
Recursive call
Sorted Sorted
FirstPart SecondPart
x<p p p≤x
Sorted
(C) GOYANI MAHESH 4
Quick Sort
88 52
14
31
25 98 30
62 23
79
88 52
14
31
25 98 30
62 23
79
14 88
98
31 30 23 ≤ 52 ≤ 62
25 79
(C) GOYANI MAHESH 6
Quick Sort
14 88
98
31 30 23 ≤ 52 ≤ 62
25 79
14,23,25,30,31 62,79,98,88
14 88
98
30 ≤ 31 ≤ 62
25 23 52 79
14,23,25,30,31,52,62,79,88,98
≤ 14 ≤ 23,25,30,31,52,62,79,88,98
A: 4 8 6 3 5 1 7 2
i=0
A: 4 8 6 3 5 1 7 2
j=1
i=0
A: 4 8 6 3 5 1 7 2
j=1
i=0
A: 4 8 6 3 5 1 7 2
j=2
i=0i=1
A: 4 8
3 6 3
8 5 1 7 2
j=3
i=1
A: 4 3 6 8 5 1 7 2
j=4
i=1
A: 4 3 6 8 5 1 7 2
j=5
i=2
A: 4 3 1
6 8 5 6
1 7 2
j=5
i=2
A: 4 3 1 8 5 6 7 2
j=6
i=2i=3
A: 4 3 1 2
8 5 6 7 8
2
j=7
i=3
A: 4 3 1 2 5 6 7 8
j=8
i=3
A: 24 3 1 4
2 5 6 7 8
A: 2 3 1 4 5 6 7 8
x<4 4≤x
Median of three
Find the first, middle and last element in the array. Use the
median of the three as the pivot.
8 1 4 9 6 3 5 2 7 0
8 1 4 9 0 3 5 2 7 6
8 1 4 9 0 3 5 2 7 6
i j
8 1 4 9 0 3 5 2 7 6
i j
8 1 4 9 0 3 5 2 7 6
i j
8 1 4 9 0 3 5 2 7 6
i j
2 1 4 9 0 3 5 8 7 6
i j
2 1 4 9 0 3 5 8 7 6
i j
2 1 4 5 0 3 9 8 7 6
j i
2 1 4 5 0 3 6 8 7 9
cn cn
cn/2 cn/2 cn
h = lg n cn/4 cn/4 cn/4 cn/4 cn
…
…
(1) #leaves = n (n)
Total(n lg n)
O( n2 ) worst case
(C) GOYANI MAHESH 30