
CSE 21
Practice Exam for Midterm 1
Spring, 2015
1. Sorting and searching Give the number of comparisons that will be performed by each sorting algo-
rithm if the input array of length nhappens to be of the form [1,2, ..., n −3, n −2, n, n −1] (i.e., sorted
except for the last two elements).
(a) MinSort (SelectionSort)
(b) BubbleSort
(c) RevisedBubbleSort
(d) InsertionSort
2. Order questions For each part, answer True or False, and give a short explanation for your answer. All
logarithms are base 2.
(a) √n3∈O(n2).
(b) 8log(n2)∈Θ(n6).
(c) log(n)∈Ω(log(log(n))).
(d) If f,g, and hare functions from the natural numbers to the non-negative real numbers with
f(n)≥g(n)∀n≥1, f(n)∈Θ(h(n)), and g(n)∈Θ(h(n)), then (f−g)(n)) ∈Θ(h(n)).
(e) If f,g, and hare functions from the natural numbers to the non-negative real numbers with
f(n)∈Θ(h(n)) and g(n)∈Θ(h(n)), then (f∗g)(n)) ∈Θ((h(n))2).
3. Analyzing an iterative algorithm In the following problem, we are given an array of salaries of em-
ployees at our firm and two numbers Land H. We wish to compute the average salary of employees
who earn between Land H(inclusive), and the number of such employees. If there are no employees
in the range, we say that 0 is the average salary. This is an iterative algorithm which takes as input
A[1, . . . , n], L, and Hand returns an ordered pair (a, N ) where ais the average salary of employees in
the range, and Nis the number of employees in the range.
AverageI nRange(A[1, . . . , n], L, H).
1. Sum ←0
2. N←0
3. FOR I= 1 TO nDO:
4. IF L≤A[I]≤HTHEN Sum ←Sum +A[I], N + +
5. IF N= 0 THEN Return (0,0)
6. Return (Sum/N, N )
(a) State a loop invariant that can be used to show the algorithm AverageInRang e is correct.
(b) Prove your loop invariant from part (a).
(c) Conclude from the loop invariant that the algorithm AverageInRang e is correct.
(d) Describe the running time of this algorithm in Big O notation, assuming that comparisons and
arithmetic operations take constant time. Justify your answer.
1