Professional Documents
Culture Documents
6.046J/18.401J LECTURE 4
Quicksort Divide and conquer Partitioning Worst-case analysis Intuition Randomized quicksort Analysis Prof. Charles E. Leiserson
September 21, 2005 Copyright 2001-5 by Erik D. Demaine and Charles E. Leiserson L4.1
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).
L4.2
Partitioning subroutine
PARTITION(A, p, q) ! A[ p . . q] x # A[ p] ! pivot = A[ p] Running Running time time i#p = =O O((n n)) for for n n for j # p + 1 to q elements. elements. do if A[ j] ! x then i # i + 1 exchange A[i] $ A[ j] exchange A[ p] $ A[i] return i
Invariant: x x p
September 21, 2005
! !x x
" "x x
? ? j q
L4.4
Example of partitioning
6 6 10 10 13 13 5 5 i j 8 8 3 3 2 2 11 11
L4.5
Example of partitioning
6 6 10 10 13 13 5 5 i j 8 8 3 3 2 2 11 11
L4.6
Example of partitioning
6 6 10 10 13 13 5 5 i j 8 8 3 3 2 2 11 11
L4.7
Example of partitioning
6 10 13 13 5 5 6 10 6 6 8 8 3 3 3 3 2 2 11 11 2 2 11 11
5 5 13 13 10 10 8 8 i j
L4.8
Example of partitioning
6 10 13 13 5 5 6 10 6 6 8 8 3 3 3 3 2 2 11 11 2 2 11 11
5 5 13 13 10 10 8 8 i j
L4.9
Example of partitioning
6 10 13 13 5 5 6 10 6 6 8 8 3 3 3 3 j 2 2 11 11 2 2 11 11
5 5 13 13 10 10 8 8 i
L4.10
Example of partitioning
6 10 13 13 5 5 6 10 6 6 6 6 8 8 3 3 3 3 2 2 11 11 2 2 11 11
5 5 13 13 10 10 8 8 5 5
3 3 10 10 8 8 13 13 2 2 11 11 i j
L4.11
Example of partitioning
6 10 13 13 5 5 6 10 6 6 6 6 8 8 3 3 3 3 2 2 11 11 2 2 11 11
5 5 13 13 10 10 8 8 5 5
3 3 10 10 8 8 13 13 2 2 11 11 i j
L4.12
Example of partitioning
6 10 13 13 5 5 6 10 6 6 6 6 6 6 8 8 3 3 3 3 2 2 11 11 2 2 11 11
5 5 13 13 10 10 8 8 5 5 5 5
3 3 10 10 8 8 13 13 2 2 11 11 3 3 2 2 i 8 8 13 13 10 10 11 11 j
L4.13
Example of partitioning
6 10 13 13 5 5 6 10 6 6 6 6 6 6 8 8 3 3 3 3 2 2 11 11 2 2 11 11
5 5 13 13 10 10 8 8 5 5 5 5
3 3 10 10 8 8 13 13 2 2 11 11 3 3 2 2 i 8 8 13 13 10 10 11 11 j
L4.14
Example of partitioning
6 10 13 13 5 5 6 10 6 6 6 6 6 6 8 8 3 3 3 3 2 2 11 11 2 2 11 11
5 5 13 13 10 10 8 8 5 5 5 5
3 3 10 10 8 8 13 13 2 2 11 11 3 3 2 2 i 8 8 13 13 10 10 11 11 j
L4.15
Example of partitioning
6 10 13 13 5 5 6 10 6 6 6 6 6 6 2 2
September 21, 2005
8 8
3 3 3 3
2 2 11 11 2 2 11 11
5 5 13 13 10 10 8 8 5 5 5 5 5 5
3 3 10 10 8 8 13 13 2 2 11 11 3 3 3 3 2 2 6 6 i 8 8 13 13 10 10 11 11 8 8 13 13 10 10 11 11
L4.16
L4.17