Processing math: 100%
Close
Close Window

DSA Coursenotes

Chapter 5 Week 6

Show Source |    | About   «  4.4. Comparison   ::   Contents   ::   5.2. Huffman Coding  »

5.1. Heaps

5.1.1. Heaps

5.1.1.1. Complete Trees

Complete binary tree node numbering
Position01234567891011Parent00112233445Left Child1357911Right Child246810Left Sibling13579Right Sibling246810

5.1.1.2. Heap insert

1 / 6 Settings
<<<>>>

Here is the process for inserting a new record into a heap.

  1. 880
  2. 851
  3. 832
  4. 723
  5. 734
  6. 425
  7. 576
  8. 67
  9. 488
  10. 609
  11. 10
Created with Raphaël 2.1.2
88
85
83
72
73
6
48
60
42
57
Proficient Saving... Error Saving
Server Error
Resubmit

5.1.1.3. Building a Heap

1 / 10 Settings
<<<>>>

Let's look at an efficient way to build the heap. We are going to make a max-heap from a set of input values.

  1. 10
  2. 21
  3. 32
  4. 43
  5. 54
  6. 65
  7. 76
Created with Raphaël 2.1.2
1
2
3
4
5
6
7
Proficient Saving... Error Saving
Server Error
Resubmit

5.1.1.4. Building a Heap Proof

1 / 13 Settings
<<<>>>

Let's look at a visualization to explain why the cost for buildheap is θ(n). We will use an example with 31 records in the heap. This means that there are 16 leaf nodes and 15 internal nodes.

Created with Raphaël 2.1.2
Created with Raphaël 2.1.2
depth 4 -------
depth 3 ----------
depth 2 ----------------
depth 1 ----------------------------
depth 0 ----------------------------------------------------
Proficient Saving... Error Saving
Server Error
Resubmit

5.1.1.5. Delete the maximum value

1 / 7 Settings
<<<>>>

Here is the process for removing the maximum value from the max heap. We know that this value is at the root (array position 0), but we also need to update the heap when we remove it.

  1. 880
  2. 851
  3. 832
  4. 723
  5. 734
  6. 425
  7. 576
  8. 67
  9. 488
  10. 609
Created with Raphaël 2.1.2
88
85
83
72
73
6
48
60
42
57
Proficient Saving... Error Saving
Server Error
Resubmit

   «  4.4. Comparison   ::   Contents   ::   5.2. Huffman Coding  »

nsf
Close Window