Homework #3

# problems
1 GT Exercise R-9.1 on page 279
Which, if any, of the algorithms bubble-sort, heap-sort, merge-sort, and quick-sort are stable?
2 CLRS Exercise 6.4-3 on page 160
What is the running time of HEAPSORT on an array A of length n that is already sorted in increasing order? What about decreasing order?
3 CLRS Exercise 6.1-1 on page 153
What are the minimum and maximum number of elements in a heap of height h?
4 CLRS Exercise 8.2-4 on page 197
Describe an algorithm that, given n integers in the range 0 to k, preprocesses its input and then answers any query about how many of the n integers fall into a range [a...b] in O(1) time.  Your algorithm should use O(n+k) preprocessing time.
5 GT Exercise C-9.6 on page 279
Let A and B be two sequences of n integers each, in the range [1,n4]. Given an integer x, describe an O(n)-time algorithm for determining if there is an integer a in A and an integer b in B such that x = a + b.

# hard problems
6 A file contains n bytes, each consisting of k bits.  You must determine how many bits in the file are 1's.  The function read() returns the next byte from the file and the function eof() returns TRUE iff there are no more bytes to be read.  You may use normal arithmetic operations and the boolean function odd(x), which returns TRUE iff x is not evenly divisible by two.
  1. Give an algorithm (call it A) which solves this problem using only O(1) space.  What is the time complexity of algorithm A as a function of n and k?
  2. Give an algorithm (call it B) which solves this problem by building a table of the number of 1's in all possible bytes.  What are the time and space complexities of algorithm B?
  3. Discuss the time-space tradeoffs between algorithms A and B for relative values of n and k.  When would you use (or not use) each?
7 Design a procedure to rotate a vector of n elements left (in place) by p positions using O(n) time and only a constant amount of extra storage. For instance, with n = 8 and p = 3, the vector ABCDEFGH is rotated to be DEFGHABC.
Hint: First, devise a procedure to reverse the elements of a subvector, and then find a series of reversals that will result in the desired rotation.

Last modified: Jan 19, 2020