Professional Documents
Culture Documents
MIDTERM EXAM #1 (Solution) : COMP 2810 Data Structures, Spring 2009 February 24, 2008
MIDTERM EXAM #1 (Solution) : COMP 2810 Data Structures, Spring 2009 February 24, 2008
MIDTERM EXAM #1 (Solution) : COMP 2810 Data Structures, Spring 2009 February 24, 2008
1. (10 pts.) Order the following functions by their growth rate from slowest to fastest:
√
N, N , N log log N, 2/N, 2N , N log(N 2 )
Solution: √
2/N, N , N, N log log N, N log(N 2 ), 2N
1
COMP 2810 Data Structures, Spring 2009 February 24, 2008
2. (15 pts.) Show the results of the following sequence of events, by drawing the state of the data structure:
where add and remove are the operations that correspond to the basic operations in a:
(a) Stack
add(4)
top
4
add(8)
top
4 8
add(1)
top
4 8 1
add(6)
top
4 8 1 6
remove()
top
4 8 1
remove()
top
4 8
2
COMP 2810 Data Structures, Spring 2009 February 24, 2008
(b) Queue
add(4)
back
front
4
add(8)
front back
4 8
add(1)
front back
4 8 1
add(6)
front back
4 8 1 6
remove()
front back
8 1 6
remove()
front back
1 6
3
COMP 2810 Data Structures, Spring 2009 February 24, 2008
add(4)
add(8)
4 8
add(1)
4 8 1
add(6)
4 8 1 6
remove()
4 8 6
remove()
8 6
4
COMP 2810 Data Structures, Spring 2009 February 24, 2008
3. (10 pts.) Consider a (singly) linked list. Describe an algorithm to remove every second element from the
list.
(a) Write a function removeEverySecond that implements the task. You can use without need to define
them all the functions that are members of the linked list class, considered in class (and in the textbook)
Solution:
The algorithm is similar to the one that is used when we delete a single node. Here though, we need
to skip an element after every deletion, and then if we have not reached the end of the list repeat this
procedure until the list is exhausted.
This can be done, for example, by:
(b) What is the running time of your algorithm on a linked list with N nodes?
Solution:
Since bN/2c elements of the list are deleted, the running time of the algorithm is O(N ).
5
COMP 2810 Data Structures, Spring 2009 February 24, 2008
4. (10 pts.) Consider the following function that computes the sum of the elements of an array iteratively:
Solution:
6
COMP 2810 Data Structures, Spring 2009 February 24, 2008
Solution:
Case 1: B ≤ A/2.
We have: A mod B < B ≤ A/2.
Case 2: B > A/2.
In this case A mod B = A − B and therefore A mod B < A − A/2 = A/2.
Since at every step of the algorithm, one of the numbers is halved (more than halved), and the algorithm
terminates once one of the numbers is equal to 1, the running time of this algorithm is at most that of the
repeated halving algorithm, which has running time of O(log N ).