Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Lecture 5
Quicksort
CS473 Lecture 5
Quicksort
Proposed by C.A.R. Hoare in 1962.
Divide-and-conquer algorithm.
Sorts in place (like insertion sort, but
not like merge sort).
Very practical (with tuning).
CS473 Lecture 5
Quicksort
1. Divide: Partition the array into 2 subarrays such
that elements in the lower part elements in the
higher part
x
p
x
q
?
i
>x
i
?
j
x
r
4
x
p
CS473 Lecture 5
?
i
time
r
5
QUICKSORT (A, p, r)
if p < r then
q H-PARTITION(A, p, r)
QUICKSORT(A, p, q)
QUICKSORT(A, q 1, r)
x
p
CS473 Lecture 5
x
q
r
6
CS473 Lecture 5
CS473 Lecture 5
7
j
i
5
i
3
j
3
i
5
j
CS473 Lecture 5
10
6
i
1
j
1
i
6
j
p
3
q
3
4
j
Termination: i 6; j 5,
CS473 Lecture 5
r
6
i
i.e., i j 1
11
7
j
i
5
i
3
j
3
i
5
j
CS473 Lecture 5
12
6
i
1
j
1
i
6
j
p
3
q
3
5
j
i
r
6
Termination: i j 5
CS473 Lecture 5
13
CS473 Lecture 5
14
>x
p
j1
i1
CS473 Lecture 5
x pivot
15
<x
p
ik-1
CS473 Lecture 5
>x
jk
ik
Cevdet Aykanat - Bilkent University
Computer Engineering Department
jk-1
16
x pivot
jk
ik-1
ik
jk-1
x pivot
>x
jk
ik-1
CS473 Lecture 5
jk-1
ik
Cevdet Aykanat - Bilkent University
Computer Engineering Department
r
17
k 1: trivial since i1 j1 p
CS473 Lecture 5
18
R1>pivot
exchange
k > 1:
L1pivot
?
pivot
pivot
after exchange
CS473 Lecture 5
j1
>pivot
R1pivot
19
Show that
Ll A[p il] pivot A[jlr] Rl if l < k
Ll A[p jl] pivot A[jl 1r] Rl if l k
Rl pivot
>pivot
Rl-1 pivot
?
p
il-1
il
jl
pivot pivot
jl-1
after exchange
CS473 Lecture 5
20
x
p
CS473 Lecture 5
Running time
is O(n)
>x
i
?
j
x
r
21
QUICKSORT (A, p, r)
if p < r then
q L-PARTITION(A, p, r)
QUICKSORT(A, p, q 1)
QUICKSORT(A, q 1, r)
x
p
CS473 Lecture 5
>x
q
Cevdet Aykanat - Bilkent University
Computer Engineering Department
r
22
7
j
7
i
2
i
CS473 Lecture 5
j
7
j
23
8
i
1
j
3
j
i
2
CS473 Lecture 5
j
7
i
24
Example: pivot = 4
3
i
7
j
i
2
p
CS473 Lecture 5
r
4
q
6
r
25
Lomuto: 1 e(n) n
26
Lomuto: ce(n) = n 1
# of index comparisons: ci(n)
n
Hoare: 1 ci(n) 2 + 1 (ci(n) e(n) + 1)
Lomuto: ci(n) n 1
CS473 Lecture 5
27
CS473 Lecture 5
28