Download MIDTERM EXAM Exercise 1 (6 pts)

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Mathematics of radio engineering wikipedia , lookup

Algorithm wikipedia , lookup

Factorization of polynomials over finite fields wikipedia , lookup

Transcript
CS3620 – SPRING 2000 – MIDTERM EXAM
Malek Mouhoub
(02/29/99)
Exercise 1 (6 pts)
The input is an N by N matrix of numbers that is already in memory. Each individual row is
increasing from left to right. Each individual column is increasing from top to bottom. Give an
O(N ) worst-case algorithm that decides if a number X is in the matrix.
Solution
Start from the top-right corner. With a comparaison, either a match is found, we
go left, or we go down.Therefore, the number of comparisons is linear.
Exercise 2 (6 pts)
The function below returns true if there are three equal integers in the array A.
int FindTriples(const Vector<int> & A) {
for (int i = 0; i < A.Length(); i++)
for (int j = i + 1; j < A.Length(); j++)
for (int k = j + 1; k < A.Length(); k++)
if (A[i] == A[j] && A[i] == A[k] && A[j] == A[k])
return 1;
return 0; }
1. What is the running time of this function ?
2. If it takes ten seconds to run FindTriples on an array of 100 elements, approximately
how long will it take to run on an array of 400 elements ?
Solution
1. O(N 3 )
2. T (400) = T (4 × 100) = 43 T (100) = 64 × 10s = 640s.
Exercise 3 (6 pts)
Consider the following function :
F1 = 2, Fn = (Fn−1 )2 n ≥ 2
1. What is the complexity of the algorithm that computes Fn using the recursive definition
given above.
2. Describe a more efficient algorithm to calculate Fn and give its running time.
Exercise 4 (4 pts)
Explain in few lines how to implement two stacks using only one array. The stack routines
should not declare an overflow unless every slot in the array is used.
Solution
Two stacks can be implemented in an array by having one grow from the low end
of the array up, and the other from the high end down.
Exercise 5 (8 pts)
The array-based stack throws an exception when the array’s capacity has been reached. Consider
the following alternative : create a larger array, using the resize method. The cost of a resize
that makes the array larger is proportional to the new size.
1. Suppose we expand the array’s capacity by one element. What is the worst-case running
time for a sequence of N insertions ?
2. Suppose we double the array’s capacity (assume the capacity is not zero). What is the
worst-case running time for a sequence of N insertions ?
3. Redo questions 1 and 2 for queues.Note that after the resize, elements may need to be
moved.
Solution
1. O(N 2 )
2. O(N )
3. O(N 2 )
4. O(N )