Introduction to Algorithms, 2022-3
Week 10: Exercises

1. Heap Insertion

A binary min-heap is initially empty. We call its insert() operation N times to add N distinct integers to the heap. How long will this take in the worst case? In the best case? What sequences of values will result in the worst-case or best-case behavior?

2. Sorted Heap

  1. Consider a sorted array. Must it be a valid min-heap?

  2. Suppose that we run heapsort on an array that is already sorted. Will any elements move?

3. Heap Check

Write a function that takes an array and returns True if the array represents a valid binary heap, otherwise False.

4. Heap Positions

Consider a binary min-heap that holds 12 values, with no duplicates.

  1. How many different array positions are possible for the second smallest value in the heap?

  2. How many different array positions are possible for the third smallest value in the heap?

  3. How many different array positions are possible for the fourth smallest value in the heap?

  4. How many different array positions are possible for the largest value in the heap?

5. Thousand Largest

Suppose we'd like to write a program that reads any number of integers from standard input, one per line. When the input ends, the program should print out the 1000 largest numbers that were seen, in sorted order. The input might contain millions or billions of integers, even more than will fit in memory. How can we do this efficiently?