# CSCI 256 Design and analysis of algorithms Assignment 5

## Due Monday, 3/5/2001

Only turn in problems from the second section.

### Practice problems:

1. An array T contains n elements. Rather than finding the ith smallest element, we want to find all of the i smallest elements for some i <= n. Find an efficient algorithm to solve the problem.

2. Let T[1..n] be a sorted array of distinct integers, some of which may be negative. Give an algorithm that can find an index i such that 1 <= i <= n and T[i] = i, given such an element exists. Your algorithm should take time O(lg n) in the worst case.

### Problems to be turned in:

1. Let T[1..n] be an array of n integers. An integer is a majority element in T if it appears strictly more than n/2 times in T. Give an algorithm to decide whether an array T[1..n] has a majority element, and, if so, find it. Your algorithm must be O(n).

2. A celebrity is defined to be someone who is known by everyone, but who does not know anyone. Let n be the number of people in a group. Find a linear time (in n) algorithm to identify the celebrity or discover that there is no celebrity. The only operation allowed is to ask someone if they know the person the asker is pointing to. Hint: Think inductively. How can you use the answer for groups of n-1 to solve the problem for groups of size n? Consider doing some (a constant amount) of work before deciding out whom to exclude from the group.

3. You have probably all run into the towers of hanoi problem. If not, it starts out with n disks of different sizes arranged on a peg in decreasing order of sizes (i.e., smallest on top). There are two other empty pegs. The goal is to move all the disks, one at a time, from the first peg to another chosen peg obeying the following rules for moves: Disks are moved from the top of one peg to another. A disk can be moved to a peg only if it is smaller than all other disks on that peg.

1. Design an algorithm (by induction of course) to find a minimal sequence of moves that solves the towers of hanoi puzzle for n disks.

2. How many moves are used in your algorithm? Construct a recurrence relation for the number of moves, and solve it.

3. Prove (by induction) that the number of moves in part b is optimal. That is, prove that there cannot exist any other algorithm that uses less moves. Hint: The key is to think about under which circumstances that largest disk can be moved.

Back to: