CmSc 250 Design and Analysis of Algorithms

advertisement
CmSc 250 Algorithms
Homework 03, due 10/06
Names:
Team work
Please, record how you solved the problems, how you scheduled your meeting times, and
who did what. For example, one person can solve a problem, and the other can check the
solution. One can write the code and another can test the program. All members can
discuss possible approaches to solving a problem. Please record how much time it took per
person per problem.
1. Show that x30 can be computed with 7 multiplications using the divide-and-conquer
approach.
(15 pts)
2. Determine the complexity for the following loops, using the Big-Oh notation: (20 pts)
n = max_el;
i = 0;
while (a[i]!= 0 && i < n) i++;
// finding the first '0' element
if (i == n)
cout << "no elements of the type to be compressed" << endl;
else
{
for (j = i + 1;j < n; j++)
{
if (a[j] !=0)
// finding the next non '0' element
{
a[i] = a[j];
// and moving it up
i = i+1;
}
}
n = i;
// new length of the array
for (j = 0; j < max_el; j++)
a[j] = b[j];
// restoring the array
}
3. Construct a complete binary tree with 8 nodes and assign the letters of COLUMBIA to
the nodes so that the name can be read in a in-order traversal.
(10 pts)
4. Consider the pseudo code of a divide-and-conquer algorithm that counts the leaves in a
binary tree. Write the recurrence relation for the run time of the algorithm for a well
balanced tree. Solve the recurrence relation to determine the efficiency class of that
algorithm. (15 pts)
1
CountLeaves(node)
{
If node == null return 0
If left and right subtrees are null return 1 // the node is a leaf
return Countleaves(root of left subtree) + CountLeaves(root of right subtree)
}
5. Suppose that we have numbers between 1 and 1000 in a binary tree and want to search
for the number 363. Which of the following sequences could not be the sequences of
nodes examined? Explain why. (10 pts)
(a) 2, 252, 401, 398, 330, 344, 400, 363.
(b) 924, 220, 911, 244, 898, 258, 362, 363.
(c) 925, 202, 911, 240, 912, 245, 363.
(d) 2, 399, 387, 219, 266, 382, 381, 278, 363.
(e) 935, 278, 347, 621, 299, 392, 358, 363.
6. Write program in Java that for a given sequence of numbers and a search value will
determine whether the sequence is a valid search sequence in a Binary Search tree. The
algorithm’s efficiency should be O(n), n – the length of the sequence. Test your program
on the sequences in problem 6. (30 pts)
At the top of the source code, write comments explaining your algorithm and provide an
analysis of the algorithm. Don’t forget to write your names at the top of the program.
Name the program so that its name starts with your first names.
Save the WORD document with the answers of the first five problems in the Java project
folder, name all files and the project folder with your first names, zip and upload to
Scholar.
2
Download