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

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

ProgramBS IT
Term3rd
Year2015
Course codeCMP-3112
AnswersSolved ✓

University of Sargodha BS IT 3rd term Data Structure & Algorithms (CMP-3112) paper, 2015 exam (80 marks, 2:30 hours). The paper is retyped below with the graph redrawn and without the handwritten ticks, followed by solved answers for all 16 short questions and all six subjective questions: Stack and List ADTs as Java interfaces with implementations, heap sort and quick sort with traces, recursion, and the adjacency list and matrix of the graph. The Java programs were compiled and run.

Solved answers

Q1 – Short answers (16 × 2)

i. Data structure. A systematic way of organising and accessing data so that operations (insert, delete, search) can be done efficiently.

ii. Reference vs primitive types (Java). Primitive types (int, double, char, boolean) store the actual value, have fixed size and are copied by value. Reference types (objects, arrays, Strings) store a reference (address) to an object on the heap; assignment copies the reference, they can be null, and == compares references (use equals() for contents).

iii. Five operations on a reference type. Assignment (=), equality comparison (== and !=), dot operator to access fields/methods (.), instanceof, type conversion (cast), and creation with new; also string concatenation with +.

iv. Abstract data type. A set of objects together with a set of operations defined on them, independent of implementation, e.g. a List ADT with insert, remove, find.

v. Call-by-reference. The function receives the address/reference of the argument, so changes inside the function affect the original variable (C++: void f(int &x)). In Java object references are passed by value, so the object can be modified through them.

vi. Stack in an array. Use an array and an integer topOfStack initialised to −1; push: arr[++top] = x; pop: return arr[top--]; when full, overflow or double the array.

vii. Collections API. A library of interfaces and classes for data structures (Java Collections Framework): interfaces Collection, List, Set, Queue, Map and implementations ArrayList, LinkedList, HashSet, TreeMap, plus algorithms like sort and iterators.

viii. Total cost of O(log N) + O(N log N). Running them one after the other, the costs add: O(log N + N log N) = O(N log N) – the larger term dominates.

ix. Array vs linked list. Advantages of arrays: O(1) random access by index, less memory per element, cache-friendly. Disadvantages: fixed size, insertion/deletion in the middle needs shifting O(n).

x. Binary tree. A tree in which every node has at most two children, called left and right child.

xi. Recursive algorithm. An algorithm that solves a problem by calling itself on smaller instances, with a base case to stop, e.g. factorial, binary search, tree traversals.

xii. Adjacency matrix vs adjacency list. Matrix: |V|×|V| array, O(V²) space, O(1) edge check – good for dense graphs. List: each vertex keeps a list of its neighbours, O(V + E) space, faster to visit all neighbours – good for sparse graphs.

xiii. Comparison-based sorting. Sorting that determines order only by comparing pairs of elements (bubble, insertion, merge, quick, heap sort). Any such algorithm needs Ω(N log N) comparisons in the worst case.

xiv. Divide-and-conquer sorts. Merge sort and quick sort (also Shell sort’s recursive variants).

xv. Hash function. Maps a key to an index (hash value) in the hash table, e.g. h(k) = k mod tableSize, distributing keys uniformly so search/insert take O(1) on average.

xvi. Heap. A complete binary tree satisfying the heap-order property: every parent ≤ its children (min-heap) or ≥ (max-heap); stored in an array; used for priority queues and heapsort.

Q2 – Stack ADT as an interface and its array implementation (Java)

interface Stack<T> {
    void push(T x);
    T pop();          // remove and return top
    T top();          // return top without removing
    boolean isEmpty();
    void makeEmpty();
}

class ArrayStack<T> implements Stack<T> {
    private T[] arr;
    private int topIndex = -1;

    @SuppressWarnings("unchecked")
    public ArrayStack() { arr = (T[]) new Object[10]; }

    public void push(T x) {
        if (topIndex + 1 == arr.length) {              // grow array when full
            arr = java.util.Arrays.copyOf(arr, arr.length * 2);
        }
        arr[++topIndex] = x;
    }
    public T pop() {
        if (isEmpty()) throw new RuntimeException("Stack underflow");
        T x = arr[topIndex];
        arr[topIndex--] = null;
        return x;
    }
    public T top() {
        if (isEmpty()) throw new RuntimeException("Stack is empty");
        return arr[topIndex];
    }
    public boolean isEmpty() { return topIndex == -1; }
    public void makeEmpty() { topIndex = -1; }
}

public class StackDemo {
    public static void main(String[] args) {
        Stack<Integer> s = new ArrayStack<>();
        for (int i = 1; i <= 12; i++) s.push(i * 10);   // causes one resize
        System.out.println("Top: " + s.top());          // 120
        System.out.println("Pop: " + s.pop());          // 120
        System.out.println("Pop: " + s.pop());          // 110
        System.out.println("Top now: " + s.top());      // 100
    }
}

Output: Top: 120, Pop: 120, Pop: 110, Top now: 100. The interface specifies the ADT (push, pop, top, isEmpty, makeEmpty); ArrayStack implements it with an array that doubles when full, so all operations are O(1) amortised.

Q3 – List ADT as an interface and its linked-list implementation (Java)

interface MyList<T> {
    void add(T x);                 // add at end
    void add(int index, T x);      // insert at position
    T get(int index);
    boolean remove(T x);
    boolean contains(T x);
    int size();
    boolean isEmpty();
}

class LinkedMyList<T> implements MyList<T> {
    private static class Node<T> {
        T data; Node<T> next;
        Node(T d, Node<T> n) { data = d; next = n; }
    }
    private Node<T> head;
    private int size;

    public void add(T x) { add(size, x); }
    public void add(int index, T x) {
        if (index < 0 || index > size) throw new IndexOutOfBoundsException();
        if (index == 0) head = new Node<>(x, head);
        else {
            Node<T> p = head;
            for (int i = 0; i < index - 1; i++) p = p.next;
            p.next = new Node<>(x, p.next);
        }
        size++;
    }
    public T get(int index) {
        if (index < 0 || index >= size) throw new IndexOutOfBoundsException();
        Node<T> p = head;
        for (int i = 0; i < index; i++) p = p.next;
        return p.data;
    }
    public boolean remove(T x) {
        Node<T> prev = null, cur = head;
        while (cur != null && !cur.data.equals(x)) { prev = cur; cur = cur.next; }
        if (cur == null) return false;
        if (prev == null) head = cur.next; else prev.next = cur.next;
        size--;
        return true;
    }
    public boolean contains(T x) {
        for (Node<T> p = head; p != null; p = p.next) if (p.data.equals(x)) return true;
        return false;
    }
    public int size() { return size; }
    public boolean isEmpty() { return size == 0; }
    public String toString() {
        StringBuilder sb = new StringBuilder("[");
        for (Node<T> p = head; p != null; p = p.next) sb.append(p.data).append(p.next != null ? ", " : "");
        return sb.append("]").toString();
    }
}

public class ListDemo {
    public static void main(String[] args) {
        MyList<String> list = new LinkedMyList<>();
        list.add("Ali"); list.add("Sara"); list.add(1, "Bilal");
        System.out.println(list + " size=" + list.size());   // [Ali, Bilal, Sara] size=3
        System.out.println("get(2) = " + list.get(2));        // Sara
        list.remove("Ali");
        System.out.println(list + " contains Sara? " + list.contains("Sara"));
    }
}

Output: [Ali, Bilal, Sara] size=3, get(2) = Sara, [Bilal, Sara] contains Sara? true. (Both Java programs were compiled with javac and run.)

Q4 – Heap sort with an example

Heap sort: (1) build a max-heap from the array (heapify from the last internal node down to the root); (2) repeatedly swap the root (maximum) with the last element of the heap, reduce the heap size by one and percolate the new root down. Time O(n log n) in all cases, in place, not stable.

Example: [4, 10, 3, 5, 1]

StepArray (heap part | sorted part)
Build max-heap10, 5, 3, 4, 1
Swap 10 ↔ 1, heapify5, 4, 3, 1 | 10
Swap 5 ↔ 1, heapify4, 1, 3 | 5, 10
Swap 4 ↔ 3, heapify3, 1 | 4, 5, 10
Swap 3 ↔ 11 | 3, 4, 5, 10
Result1, 3, 4, 5, 10

Q5 – Quick sort with an example

QUICKSORT(A, lo, hi)
  if lo < hi
      p = PARTITION(A, lo, hi)
      QUICKSORT(A, lo, p - 1)
      QUICKSORT(A, p + 1, hi)

PARTITION(A, lo, hi)        // Lomuto, pivot = last element
  pivot = A[hi]; i = lo - 1
  for j = lo to hi - 1
      if A[j] <= pivot: i = i + 1; swap A[i], A[j]
  swap A[i + 1], A[hi]
  return i + 1

Example: [36, 15, 47, 8, 24, 59, 12]

PivotArray after partition
128, 12, 47, 36, 24, 59, 15
15 (right part)8, 12, 15, 36, 24, 59, 47
478, 12, 15, 36, 24, 47, 59
248, 12, 15, 24, 36, 47, 59

Sorted: 8, 12, 15, 24, 36, 47, 59. Average O(n log n); worst case O(n²) (already sorted input with last-element pivot); median-of-three pivot avoids the worst case. (Traces generated by a program.)

Q6 – Recursion with an example

A recursive algorithm has (1) a base case solved directly and (2) a recursive case that calls itself on a smaller problem that moves toward the base case.

#include <iostream>
using namespace std;

long long factorial(int n) {
    if (n <= 1) return 1;               // base case
    return n * factorial(n - 1);        // recursive call
}

int main() {
    int n;
    cout << "Enter a non-negative number: "; cin >> n;
    if (n < 0) cout << "Factorial of negative number is not defined\n";
    else cout << n << "! = " << factorial(n) << endl;
    return 0;
}

Trace for 4: factorial(4) = 4 × factorial(3) = 4 × 3 × factorial(2) = 4 × 3 × 2 × factorial(1) = 24. Other examples: Fibonacci, binary search, Towers of Hanoi, tree traversals. Rules: always progress toward the base case and avoid redundant recomputation.

Q7 – Adjacency list and matrix of the graph

Directed weighted edges: V0→V1 (2), V0→V3 (1), V1→V3 (3), V1→V4 (10), V2→V0 (4), V2→V5 (5), V3→V2 (2), V3→V4 (2), V3→V5 (8), V3→V6 (4), V4→V6 (6), V6→V5 (1).

Adjacency list (neighbour, weight):

V0: V1(2) -> V3(1)
V1: V3(3) -> V4(10)
V2: V0(4) -> V5(5)
V3: V2(2) -> V4(2) -> V5(8) -> V6(4)
V4: V6(6)
V5: (none)
V6: V5(1)

Adjacency matrix (weight, ∞/– = no edge):

V0V1V2V3V4V5V6
V0–2–1–––
V1–––310––
V24––––5–
V3––2–284
V4––––––6
V5–––––––
V6–––––1–
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.