set6_quicksort
set6_quicksort
QUICKSORT
1
Quicksort
2
Quicksort
• It sorts in place.
3
Quicksort Algorithm
L x G
x
Example
A 2 8 7 1 3 5 6 4
5
𝑖 𝑝𝑗 𝑟
Partition Step1 2 8 7 1 3 5 6 4
𝑝 𝑖 𝑗 𝑟
Step2 2 8 7 1 3 5 6 4
𝑝 𝑖 𝑗 𝑟
Step3 2 8 7 1 3 5 6 4
𝑝 𝑖 𝑗 𝑟
Step4 2 8 7 1 3 5 6 4
6
𝑝 𝑖 𝑗 𝑟
2 1 7 8 3 5 6 4
Partition
Step5
𝑝 𝑖 𝑗 𝑟
Step6 2 1 3 8 7 5 6 4
𝑝 𝑖 𝑗 𝑟
Step7 2 1 3 8 7 5 6 4
𝑝 𝑖 𝑟
Step8 2 1 3 8 7 5 6 4
𝑝 𝑖 𝑟
Step9 2 1 3 4 7 5 6 8
7
Example
2 8 7 1 3 5 6 4
2 1 3 4 7 5 6 8
2 1 3 7 5 6 8
1 2 5 6 7
8
Performance of Quicksort
10
Worst Case
Partitioning 𝑛
0 𝑛-1
0 𝑛−2
Partition Complexity
11
Worst Case Partitioning
Height = 0 𝑛
one of size − 1.
𝑛 𝑛
−1
2 2
𝒏
𝟐
14
Best Case
Partitioning
Using case 2:
Then
15
Average Case Partitioning
16
Average
Shortest Path Longest Path
Case Ω Ο
Partitioning
. . . .
. . . .
17
Shortest Path
1 𝑛 𝑛 9𝑛
10 + =𝑛
10 10
𝑛 9𝑛
2 𝑛 𝑛 9𝑛 9𝑛 81𝑛 Height = 1
+ + + =𝑛 10 10
100 100 100 100 100
… … …
… … … 𝑛 9𝑛 9𝑛 81𝑛
Height = 2 100 100 100 100
𝑘 𝑛 𝑛
=1
10 . . . . .
.
. . . .
𝑛
= 1 → 10 = 𝑛 → 𝑘 = log 𝑛 Height = k?
𝑇(1) 𝑇(1) 𝑇(1) 𝑇(1)
10
18
Shortest Path
+ +
Height 𝒏 Cost of level
0 𝑛 𝑛
1 𝑛 𝑛 9𝑛
10 + =𝑛
10 10
2 𝑛 𝑛 9𝑛 9𝑛 81𝑛
100 + + + =𝑛
100 100 100 100
… … …
… … …
𝑘 𝑛 𝑛
=1
10
𝑛
= 1 → 10 = 𝑛 → 𝑘 = log 𝑛
10
19
Longest Path
1 9𝑛 𝑛 9𝑛
+ =𝑛
10 10 10
𝑛 9𝑛
2 81𝑛 𝑛 9𝑛 9𝑛 81𝑛 Height = 1 10 10
+ + + =𝑛
100 100 100 100 100
… … …
… … … 𝑛 9𝑛 9𝑛 81𝑛
Height = 2 100 100 100 100
𝑘 9 𝑛
( ) 𝑛=1 .
10 . . . .
.
. . . .
9 10 𝑇(1) 𝑇(1) 𝑇(1) 𝑇(1)
( ) 𝑛 = 1 → ( ) = 𝑛 → 𝑘 = log 𝑛 Height = k?
10 9
20
Longest Path
+ +
Height 𝒏 Cost of level
0 𝑛 𝑛
1 9𝑛 𝑛 9𝑛
+ =𝑛
10 10 10
2 81𝑛 𝑛 9𝑛 9𝑛 81𝑛
+ + + =𝑛
100 100 100 100 100
… … …
… … …
𝑘 9 𝑛
( ) 𝑛=1
10
9 10
( ) 𝑛 = 1 → ( ) = 𝑛 → 𝑘 = log 𝑛
10 9
21
Average Case Partitioning
𝑛 Θ(𝑛) 𝑛
𝑛−1 𝑛−1
0 𝑛-1 −1
2 2
𝑛−1 𝑛−1
−1
2 2 In average:
22
Randomized Version of Quicksort
24
Randomized Quicksort Algorithm
L x G
x
Average case: