6. Extended Example To sort the following numbers in increasing order: 34 8 64 51 32 21 P = 1; Look at first element only, no change. P = 2; tmp = 8; 34 > tmp, so second element is set to 34. We have reached the front of the list. Thus, 1st position = tmp After second pass: 8 34 64 51 32 21 (first 2 elements are sorted)
7. P = 3; tmp = 64; 34 < 64, so stop at 3 rd position and set 3 rd position = 64 After third pass: 8 34 64 51 32 21 (first 3 elements are sorted) P = 4; tmp = 51; 51 < 64, so we have 8 34 64 64 32 21, 34 < 51, so stop at 2nd position, set 3 rd position = tmp, After fourth pass: 8 34 51 64 32 21 (first 4 elements are sorted) P = 5; tmp = 32, 32 < 64, so 8 34 51 64 64 21, 32 < 51, so 8 34 51 51 64 21, next 32 < 34, so 8 34 34, 51 64 21, next 32 > 8, so stop at 1st position and set 2 nd position = 32, After fifth pass: 8 32 34 51 64 21 P = 6; tmp = 21, . . . After sixth pass: 8 21 32 34 51 64
28. Binary trees A complete tree An almost complete tree A complete binary tree is one where a node can have 0 (for the leaves) or 2 children and all leaves are at the same depth.
29.
30.
31. Proof Prove by induction that number of nodes at depth d is 2 d Total number of nodes of a complete binary tree of depth d is 1 + 2 + 4 +…… 2 d = 2 d+1 - 1 Thus 2 d+1 - 1 = N d = log(N + 1) - 1 = O(log N) What is the largest depth of a binary tree of N nodes? N
32. Coming back to Heap Heap property: the value at each node is less than or equal to that of its descendants. not a heap A heap 4 2 5 6 1 3 1 2 5 6 4 3
33.
34.
35. Insert 2.5 Percolate up to maintain the heap property 1 2 5 6 4 3 1 2 5 6 4 3 2.5 1 2 2.5 6 4 3 5
38. DeleteMin: first attempt Delete the root. Compare the two children of the root Make the lesser of the two the root. An empty spot is created. Bring the lesser of the two children of the empty spot to the empty spot. A new empty spot is created. Continue
39. Heap property is preserved, but completeness is not preserved! 1 2 5 6 4 3 2 5 6 4 3 2 5 6 4 3 2 3 5 6 4