Академический Документы
Профессиональный Документы
Культура Документы
Quick-Sort 1 Quick-Sort 2
Quick-Sort Partition
Quick-sort is a randomized We partition an input Algorithm partition(S, p)
sequence as follows: Input sequence S, position p of pivot
sorting algorithm based x We remove, in turn, each Output subsequences L, E, G of the
on the divide-and-conquer element y from S and elements of S less than, equal to,
or greater than the pivot, resp.
paradigm: We insert y into L, E or G,
L, E, G ← empty sequences
Divide: pick a random depending on the result of
x ← S.remove(p)
element x (called pivot) and the comparison with the
x pivot x while ¬S.isEmpty()
partition S into y ← S.remove(S.first())
L elements less than x
Each insertion and removal
if y < x
is at the beginning or at the
E elements equal x L E G L.insertLast(y)
end of a sequence, and
G elements greater than x else if y = x
hence takes O(1) time
Recur: sort L and G E.insertLast(y)
Thus, the partition step of else { y > x }
Conquer: join L, E and G x quick-sort takes O(n) time G.insertLast(y)
return L, E, G
Quick-Sort 3 Quick-Sort 4
9→9 4→4
2→2 9→9
Quick-Sort 5 Quick-Sort 6
Quick-Sort 4/9/2002 10:1
2 4 3 1→ 2 4 7 9 3 8 6 1 → 1 3 8 6 2 4 3 1 →→ 2 4 7 3 8 6 1 → 1 3 8 6
Quick-Sort 7 Quick-Sort 8
2 4 3 1 → 1 2 3 4 3 8 6 1 → 1 3 8 6 2 4 3 1 → 1 2 3 4 7 9 7 1 → 1 3 8 6
Quick-Sort 9 Quick-Sort 10
2 4 3 1 → 1 2 3 4 7 9 7 1 → 1 3 8 6 2 4 3 1 → 1 2 3 4 7 9 7 → 17 7 9
Quick-Sort 11 Quick-Sort 12
Quick-Sort 4/9/2002 10:1
n + (n − 1) + … + 2 + 1
2 4 3 1 7 9 7 1 → 1 1 7294376
Thus, the worst-case running time of quick-sort is O(n2)
depth time Good call Bad call
Quick-Sort 15 Quick-Sort 16
Quick-Sort 17