DSA - Data Structure & Algorithms, Past Papers, UOS Main Campus

Data Structures and Algorithms Past Paper 2018 – BS IT 3rd Term UOS (CMP-3112)

ProgramBS IT
Term3rd
Year2018
Course codeCMP-3112
AnswersSolved ✓

University of Sargodha BS IT 3rd term Data Structure & Algorithms (CMP-3112) paper, 2018 exam (80 marks, 2:30 hours). The paper has been retyped without the candidate’s roll number, and solved answers are given below for all 16 short questions and all subjective questions: recursion, merge sort, AVL tree with rotations, hashing collisions, min-heap insertion, bubble sort and linked list code.

Solved answers

Q1 – Short answers (16 × 2)

i. Nodes in a heap of height h: A heap is a complete binary tree. With the root at height 0, the maximum is 2h+1 − 1 nodes (last level full) and the minimum is 2h nodes (only one node on the last level).

ii. Possible binary search sequence: Only (a). In binary search each new value must lie between the bounds set so far. In (b), after 911 the search goes left (363 < 911), so 912 cannot come next; in (c), after 347 the search goes right (all next values must be > 347), but 299 comes later.

iii. Sequences that could not be examined: (b) and (c), for the same reasons as in (ii); sequence (a) is a valid search path in a BST. (All three checked with a Python program.)

iv. Insertion sort of 11, 9, 15, 8, 13, 6: Pass 1: 9 11 15 8 13 6 → pass 2: 9 11 15 8 13 6 → pass 3: 8 9 11 15 13 6 → pass 4: 8 9 11 13 15 6 → pass 5: 6 8 9 11 13 15.

v. Postfix 65*432+1-/+ to infix: Treating each digit as an operand: 6 5 * → (6 * 5); 3 2 + → (3 + 2); then (3 + 2) − 1; 4 / ((3 + 2) − 1); finally (6 * 5) + (4 / ((3 + 2) − 1)), which evaluates to 30 + 1 = 31.

vi. Full binary tree of height 3: Taking a full (perfect) binary tree with root at height 0: leaves = 23 = 8 and internal nodes = 23 − 1 = 7 (15 nodes in total).

vii. Recursion vs iteration: Advantages: shorter, clearer code for naturally recursive problems (trees, divide and conquer, backtracking). Disadvantages: extra memory for the call stack, overhead of function calls, risk of stack overflow, usually slower than a loop.

viii. Is xy-z- = xyz–? False. xy-z- means (x − y) − z, while xyz– means x − (y − z) = x − y + z. They are equal only when z = 0.

ix. Graph vs tree: A tree is a connected acyclic graph with exactly one path between any two nodes, a root, and n − 1 edges for n nodes. A graph may have cycles, may be disconnected, has no root and any number of edges.

x. Complete binary tree: A binary tree in which every level is completely filled except possibly the last, and the last level’s nodes are as far left as possible (e.g. a heap).

xi. Abstract data type (ADT): A logical description of data and the operations on it, independent of implementation, e.g. a Stack ADT with push, pop, peek and isEmpty.

xii. Stable sorting: A sort is stable if records with equal keys keep their original relative order after sorting, e.g. insertion, bubble and merge sort are stable; selection and heap sort are not.

xiii. In-place algorithm: An algorithm that transforms its input using only a constant (O(1)) amount of extra memory, e.g. insertion, selection, bubble and heap sort; merge sort is not in-place.

xiv. Insertion vs selection sort: Insertion sort inserts each element into the already-sorted part by shifting; it is stable and O(n) for sorted input. Selection sort selects the minimum of the unsorted part and swaps it; it always makes O(n²) comparisons but only n − 1 swaps, and is not stable.

xv. Data structure vs algorithm: A data structure is a way to organise and store data (array, tree); an algorithm is a finite step-by-step procedure to solve a problem using that data (sorting, searching).

xvi. Time complexity of linear search: Best case O(1), average and worst case O(n).

Q2 – Recursion and merge sort

(a) Sum of squares of the first n positive integers, 1² + 2² + … + n²:

All C++ code below was compiled with g++ and tested.

int sumOfSquares(int n) {
    if (n == 0) return 0;                 // base case
    return n * n + sumOfSquares(n - 1);   // recursive case
}
// sumOfSquares(4) = 16 + 9 + 4 + 1 = 30

(b) Merge sort procedure (divide and conquer): (1) If the list has 0 or 1 element it is sorted. (2) Divide the list into two halves at the middle. (3) Recursively sort each half. (4) Merge the two sorted halves by repeatedly taking the smaller front element. Time O(n log n) in all cases, extra space O(n), stable.

void merge(int a[], int l, int m, int r) {
    vector<int> L(a + l, a + m + 1), R(a + m + 1, a + r + 1);
    int i = 0, j = 0, k = l;
    while (i < (int)L.size() && j < (int)R.size())
        a[k++] = (L[i] <= R[j]) ? L[i++] : R[j++];
    while (i < (int)L.size()) a[k++] = L[i++];
    while (j < (int)R.size()) a[k++] = R[j++];
}
void mergeSort(int a[], int l, int r) {
    if (l >= r) return;            // one element: already sorted
    int m = (l + r) / 2;
    mergeSort(a, l, m);            // sort left half
    mergeSort(a, m + 1, r);        // sort right half
    merge(a, l, m, r);             // merge the two sorted halves
}

Example: 38 27 43 3 → (38 27)(43 3) → (27 38)(3 43) → 3 27 38 43.

Q3 – AVL tree and collisions

(a) Inserting 15, 4, 13, 6, 17, 2, 11:

Insert 15:   15
Insert 4:    15
            /
           4
Insert 13:   15          LR imbalance at 15 (balance +2, 13 is in the right subtree of 4)
            /            1) left-rotate 4    2) right-rotate 15
           4                    15                  13
            \                  /                  /  \
             13              13                  4    15
                            /
                           4
Insert 6:       13
               /  \
              4    15
               \
                6
Insert 17:      13
               /  \
              4    15
               \     \
                6     17
Insert 2:       13
               /  \
              4    15
             / \     \
            2   6     17
Insert 11:      13
               /  \
              4    15
             / \     \
            2   6     17
                 \
                  11      (all balance factors are −1, 0 or +1)

Only one rotation (a double LR rotation at 15 when 13 was inserted) is needed. Final AVL tree: root 13; 4 with children 2 and 6 (6 has right child 11); 15 with right child 17. Checked with a Python AVL program.

(b) Collision occurs when two different keys hash to the same slot (h(k₁) = h(k₂)). Ways to deal with collisions:

  • Separate chaining: each slot keeps a linked list of all keys hashing to it.
  • Open addressing – linear probing: try the next slots (h + 1, h + 2, …) until an empty one is found.
  • Quadratic probing: try h + 1², h + 2², h + 3², … to reduce clustering.
  • Double hashing: use a second hash function for the step size: h + i·h₂(k).
  • Rehashing: when the table becomes too full, create a larger table and reinsert all keys.

Q4 – Min-heap insertion and MIN-HEAPIFY

(a) Array (index 0 based): 35, 55, 99, 66, 88, 120, 110, 122, 180. Insert 4 at the end (index 9) and bubble it up while it is smaller than its parent (parent of i = ⌊(i − 1)/2⌋):

StepActionArray
1Add 4 at index 9 (parent 88 at index 4)35 55 99 66 88 120 110 122 180 4
24 < 88, swap35 55 99 66 4 120 110 122 180 88
34 < 55 (index 1), swap35 4 99 66 55 120 110 122 180 88
44 < 35 (root), swap4 35 99 66 55 120 110 122 180 88
Final min-heap:            4
                         /     \
                       35       99
                      /  \     /  \
                    66    55  120  110
                   /  \   /
                 122 180 88

(b) MIN-HEAPIFY(A, n, i) – makes the subtree rooted at i a min-heap, assuming its children are already min-heaps:

MIN-HEAPIFY(A, n, i)
1  smallest = i
2  l = 2i + 1,  r = 2i + 2
3  if l < n and A[l] < A[smallest]  then smallest = l
4  if r < n and A[r] < A[smallest]  then smallest = r
5  if smallest ≠ i
6      swap A[i] and A[smallest]
7      MIN-HEAPIFY(A, n, smallest)

It runs in O(log n) time.

Q5 – Bubble sort

(a) After each pass the largest remaining element “bubbles” to the end:

PassList after the pass
Start14 9 11 5 7 10 2 15 20 17
19 11 5 7 10 2 14 15 17 20
29 5 7 10 2 11 14 15 17 20
35 7 9 2 10 11 14 15 17 20
45 7 2 9 10 11 14 15 17 20
55 2 7 9 10 11 14 15 17 20
62 5 7 9 10 11 14 15 17 20
7no swaps – list is sorted, stop

Sorted: 2, 5, 7, 9, 10, 11, 14, 15, 17, 20 (passes checked with a Python program).

(b)

All C++ code below was compiled with g++ and tested.

void bubbleSort(int a[], int n) {
    for (int pass = 0; pass < n - 1; pass++) {
        bool swapped = false;
        for (int j = 0; j < n - 1 - pass; j++)
            if (a[j] > a[j + 1]) {
                int t = a[j]; a[j] = a[j + 1]; a[j + 1] = t;
                swapped = true;
            }
        if (!swapped) break;          // already sorted
    }
}

Q6 – Linked list code

All C++ code below was compiled with g++ and tested.

(a) Insert at the end of a doubly circular linked list (the last node is head->prev):

struct DNode { int data; DNode* prev; DNode* next; };

void insertEnd(DNode*& head, int x) {
    DNode* n = new DNode{x, nullptr, nullptr};
    if (head == nullptr) {             // empty list: node points to itself
        n->next = n->prev = n;
        head = n;
        return;
    }
    DNode* last = head->prev;
    n->next = head;
    n->prev = last;
    last->next = n;
    head->prev = n;
}

(b) Delete the node having value 15 from a singly linked list – call deleteValue(head, 15):

struct Node { int data; Node* next; };

bool deleteValue(Node*& head, int key) {
    if (head == nullptr) return false;
    if (head->data == key) {                 // 15 is in the first node
        Node* t = head; head = head->next; delete t; return true;
    }
    Node* p = head;
    while (p->next != nullptr && p->next->data != key) p = p->next;
    if (p->next == nullptr) return false;    // 15 not found
    Node* t = p->next;
    p->next = t->next;                       // bypass the node
    delete t;
    return true;
}
Save this paper for offline studyDownload the question paper, or save the paper together with all solved answers as a PDF.
↓ Download Paper (JPG)

About Saif R

An educator and technology enthusiast passionate about empowering students through quality education and digital learning. Dedicated to making academic resources and opportunities accessible to everyone.