Midsemester Exam Solutions
Midsemester Exam Solutions
Midsemester Exam Solutions
a) Why is it not a good idea to use execution time as a measure of the speed of an
algorithm? Suggest an alternative measure and explain why it is better.
b) Briefly explain the meaning of, and give the formal definitions for:
i. Ω-notation
Page 1 of 6
c) For each of the following pieces of code, state and prove the big-O complexity
in terms of the size of the data n (consider assignment statements only).
Remember that to prove the complexity you must find values for the constants
c and N that satisfy the formal mathematical definition.
i. z = 0;
for (x = 0; x < n; x++)
for (y = 0; y < n; y += 2)
z++;
f(n) = 21 = O(1)
Only term biggest for all n>0
c ≥ 21
Therefore N=0, c=41
Page 2 of 6
v. for (x = 0, sum = 0; x < n; x++)
for (y = 0; y < n; y++)
for (z = 0; z < n; z++)
sum += x * y * z;
Page 3 of 6
Question 2 - Linked Lists (21 marks)
a) Compare and contrast static and dynamic data structures. Give an example of
each.
class IntSLLNode {
public:
int info;
IntSLLNode *next;
IntSLLNode(int el, IntSLLNode *ptr = 0) {
info = el; next = ptr;
}
};
class IntSLList {
public:
IntSLList() {head = tail = 0;}
~IntSLList();
int isEmpty() {return head == 0;}
void addToHead(int);
void addToTail(int);
int deleteFromHead(); // del. head & return its info
int deleteFromTail(); // del. tail & return its info
void deleteNode(int);
bool isInList(int) const;
void printAll() const;
private:
IntSLLNode *head, *tail;
};
b) Explain the reason for having two access pointers (head and tail) in the
IntSLList class.
Page 4 of 6
c) Write code for the function body of addToTail. The function should add a
new node to the end of the list, and update the tail pointer accordingly. Think
about what special cases that must be considered.
Page 5 of 6
ii. Deleting a node from the beginning of the singly-linked list.
e) Briefly describe the operation of a skip list. You should describe, using a
diagram, how nodes are connected together, and also how the search algorithm
works. What is the advantage of a skip list over a normal linked list?
See handout 2 for description of skip list. The advantage over a normal
linked list is that the search complexity is reduced.
END OF EXAMINATION
Page 6 of 6