

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!


1
What do these
words have in
common?
Banana
Dresser
Grammar
Potato
Revive
Uneven
Assess
2
Reversing array segment b[h..k]
reversed
h j k
post: b
b not reversed
h k
pre:
b 1 2 3 4 5 6 7 8 9 9 9 9
h k
b9 9 9 9 8 7 6 5 4 3 2 1
h k
3
Sorting:
0 n
pre: b sorted
0 n
post: b
sorted?
insertion sort 0 i n
inv: b
“sorted” means in ascending order
0 i
0 i
2
b[0..i-1]: i elements
in worst case:
Iteration 0: 0 swaps
Iteration 1: 1 swap
Iteration 2: 2 swaps
4
0 n
pre: b sorted
0 n
post: b
Add property to invariant: first segment contains smaller values.
≤ b[i..], sorted ≥ b[0..i-1],?
0 i n
invariant: b
selection sort
sorted?
0 i n
invariant: b
insertion sort
i n
i n
2
5
Quicksort /** Sort b[h..k] */
public static void qsort (int [] b, int h, int k ) {
if (b[h..k] has fewer than 2 elements)
return;
j= partition(b, h, k);
<= x x >= x
h j k
post: b
x?
h k
pre: b
int j= partition(b, h, k);
// b[h..j–1] <= b[j] < b[j+1..k]
// Sort b[h..j–1] and b[j+1..k]
qsort(b, h, j–1);
qsort(b, j+1, k);
To sort array of size n. e.g. 2
15
Worst case: n
2 e.g. 2
30
Average case:
n log n. e.g. 15 * 2 15
15 = 32768
6
Tony Hoare,
in 1968
Quicksort author
Tony Hoare,
in 2007
in Germany
8
9
10
11
12
Sir Tony Hoare, Fritz Bauer
Quicksort author My advisor
Pioneer in computing in the 50's,
60's. Developer of the historical
computing section of the
Deutsches Museum
Marienplatz, Munich
th