Heap & HeapSort


(Supplement) Trees

1. Basic Concepts


2. Binary Trees


3. Mathematical Properties of binary trees

  1. Number of nodes on each level i is at most 2i
    • level 0: 20 = 1 ... root
    • level 1: 21 = 2
    • level 2: 22 = 4

    Those are upper bound numbers which hold when a tree is fully expanded (i.e., a tree of depth d is complete and all nodes at depth 0 through d-1 have two children).

  2. Total number of nodes in a (general) binary tree of depth d is
    • upper bound: 20 + 21 + 22 + .. + 2d = 2d+1 -1 (by geometric sequence) -- when a tree is fully expanded
    • lower bound: d + 1 -- when all internal nodes have 1 child (called a degenerate tree)

  3. Depth (or height) of a binary tree with N nodes >= floor(lgN)
    • lower bound: floor(lgN) .. when a tree is fully expanded
    • upper bounf: N - 1 .. , when a tree is a degenerate tree

      e.g. floor(lg31) = 4

EXERCISES:

  1. How many nodes are in a fully expanded binary tree of depth 5? Of them, how many are internal, and how many are leaf nodes?

     

  2. What is the depth of a complete binary tree with 200 nodes?
     


Priority Queues (Heaps)

1. Basic concepts


2. Heap Insertion

EXERCISE: Assume that the array representing a min binary heap contains the values 2, 8, 3, 10, 16, 7, 18, 13. Show the contents of the array after inserting the value 4.


3. Heap Deletion

EXERCISE: Assume that the array representing a min binary heap contains the values 2, 8, 3, 10, 16, 7, 18, 13. Show the contents of the array after deleting the minimum element.


4. Heap Construction

EXERCISE: Show the array representing the min binary heap constructed using the initial values 18, 2, 13, 10, 15, 3, 7, 16, 8.


5. Heap Sort

EXERCISE: Given an array [17, 23, 10, 1, 7, 16, 9, 20], sort it on paper using heapsort. Write down explicitly each step.