Homework #3 -- due Wednesday Wk 3

# required problems topic
1 CLR Problem 8-2(e) on page 179 in situ sort
2 (Baase Exercise 5.22 on page 246)
(a) You are given N keys and an integer K such that 1 < K < N. Give an efficient algorithm to find any one of the K smallest keys.  How many key comparisons does your algorithm do?
(b) Give a lower bound, as a function of N and K, on the number of comparisons needed to solve this problem.
lower bound on select
3 Let A be an array of size n of integers, where A[1] < A[2] < ... < A[n].
(Note that each entry may be a positive or negative integer.)

(a) Give an algorithm that takes O(log n) time to find an i such that A[i] = i, provided such an i exists. If no such i exists, the algorithm returns 0.

(b) Prove that any algorithm to solve this problem must take time Ω(log n).
search

# suggested problems topic
4 Baase Exercise 5.3 on page 242 lower bound on maxmin
5 Baase Exercise 4.46 on page 215 radix sort
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?
time-space trade-off
7* Describe an algorithm that, given n integers in the range 1 to k, preprocesses its input and then answers in O(1) time any query about how many of the n integers fall into a range [a...b].  The preprocessing phase must run in O(n+k) time. range query
8* 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.
 


Dan Hirschberg
Computer Science Department
University of California, Irvine, CA 92697-3435
dan at ics.uci.edu
Last modified: Jun 18, 2008