CS221: Algorithms and Data Structures Sorting Takes Priority
Steve Wolfman (minor tweaks by Alan Hu)
1
CS221: Algorithms and Data Structures Sorting Takes Priority Steve - - PowerPoint PPT Presentation
CS221: Algorithms and Data Structures Sorting Takes Priority Steve Wolfman (minor tweaks by Alan Hu) 1 Todays Outline Sorting with Priority Queues, Three Ways 2 How Do We Sort with a Priority Queue? You have a bunch of data. You
1
2
insert deleteMin
3
Sort(elts): pq = new PQ for each elt in elts: pq.insert(elt); sortedElts = new array of size elts.length for i = 0 to elts.length – 1: sortedElts[i] = pq.deleteMin return sortedElts
4
Sort(elts): pq = new PQ for each elt in elts: pq.insert(elt); sortedElts = new array of size elts.length for i = 0 to elts.length – 1: sortedElts[i] = pq.deleteMin return sortedElts
5
6
1 2 3 4 5 6 7 8 9 10 11 12 13
1 2 3 4 5 6 7 8 9 10 11 12 13
1 2 3 4 5 6 7 8 9 10 11 12 13
1 2 3 4 5 6 7 8 9 10 11 12 13
1 2 3 4 5 6 7 8 9 10 11 12 13
1 2 3 4 5 6 7 8 9 10 11 12 13
1 2 3 4 5 6 7 8 9 10 11 12 13
14
1 2 3 4 5 6 7 8 9 10 11 12 13
15
16
1 2 3 4 5 6 7 8 9 10 11 12 13
17
18
1 2 3 4 5 6 7 8 9 10 11 12 13
19
1 2 3 4 5 6 7 8 9 10 11 12 13
20
21
Note: 9 ends up being perc’d down as well since its invariant is violated by the time we reach it.
22
1 2 8 9 10 6 3 12 14 13 20 7 5 4 1 2 8 9 7 6 3 12 10 13 14 5 4
1 2 8 5 7 6 3 9 10 12 13 4
1 2 4 5 7 6 3 8 10 9 12
2 4 5 1 6 3 8 7 9 10
4 2 1 6 3 5 7 8 9
4 2 1 6 3 5 7 8 9
24
Sort(elts): pq = new PQ for each elt in elts: pq.insert(elt); sortedElts = new array of size elts.length for i = 0 to elements.length – 1: sortedElts[i] = pq.deleteMin return sortedElts
25
26
27
28
29
30
1 2 3 4 5 6 7 8 9 10 11 12 13
31
32
33
34
1. Consider the two halves to be queues. 2. Repeatedly compare the fronts of the queues. Whichever is smaller (or, if one is empty, whichever is left), dequeue it and insert it into the result.
35
1. Consider the two halves to be queues. 2. Repeatedly compare the fronts of the queues. Whichever is smaller (or, if one is empty, whichever is left), dequeue it and insert it into the result.
36
37
3
7 5 9 6 2 1 3
7 5 9 6 2 1 3
7 5 9 6 2 1 3
7 5 9 6 2 1
3 5 7 6 9 1 2
3 5 7 1 2 6 9
1 2 3 5 6 7 9
38
39
40
3
7 5 9 6 2 1
3
3 7 5 9 6 2 1 x: tmp: x: merge( x, 0, 0, 1, tmp ); // step * merge( x, 4, 5, 7, tmp ); // step **
3 5 7 6 9 1 2
3 5 7 1 2 6 9 x: tmp: x: 1 2 6 9 merge( x, 0, 3, 7, tmp ); // will be the final step
41
42
43
44
1
2 3 5 4 7 left partition right partition
45
46
47
48
2
6 1 5
3 7
49
50
51
52
53
54
55
56
57 (not asymptotic)
58
59
60
61
62
63
64