3 Divide And Conquer Algorithms

Design and Analysis of Algorithms ยท Unit 3 ยท 8 hrs

Divide and Conquer Algorithms

Exam-focused notes for Divide and Conquer Algorithms (Design and Analysis of Algorithms, CSC325): what the TU syllabus asks and how it has actually been tested, with 10 solved past questions from this unit.

Divide and Conquer Algorithms in short

Divide and conquer solves a problem by splitting it into smaller sub-problems of the same kind, solving each recursively, and combining their solutions. This unit applies the strategy to searching, to the three classic $O(n \log n)$ sorts, and to the order statistics (selection) problem, and shows how to derive and solve the recurrence each one produces.

Divide and Conquer Algorithms: notes

Searching Algorithms: Binary Search, Min-Max Finding and their Analysis

Binary search looks for a key in a sorted array by comparing it with the middle element and recursing into the half of the array that could still contain it.

int binarySearch(int a[], int l, int r, int key) {
    if (l > r) return -1;
    int m = (l + r) / 2;
    if (a[m] == key) return m;
    if (key < a[m]) return binarySearch(a, l, m - 1, key);
    return binarySearch(a, m + 1, r, key);
}

Each call does $O(1)$ work and recurses into an array half the size, giving the recurrence $T(n) = T(n/2) + O(1)$, which was solved in Unit 1 by the recursion tree method to $T(n) = \Theta(\log n)$. The best case is $O(1)$, when the key is at the middle on the first call; the worst case, when the key is absent or at an endpoint, and the average case are both $\Theta(\log n)$.

Min-max finding locates both the smallest and largest element of an array. The naive iterative scan compares every element against the running maximum and minimum separately, using $2(n-1)$ comparisons, so $O(n)$ time. The divide and conquer version splits the array in half, finds the min and max of each half recursively, and combines them with two comparisons:

void minMax(int a[], int l, int r, int *min, int *max) {
    if (l == r) { *min = *max = a[l]; return; }
    if (l == r - 1) {
        if (a[l] < a[r]) { *min = a[l]; *max = a[r]; }
        else { *min = a[r]; *max = a[l]; }
        return;
    }
    int mid = (l + r) / 2, min1, max1, min2, max2;
    minMax(a, l, mid, &min1, &max1);
    minMax(a, mid + 1, r, &min2, &max2);
    *min = min1 < min2 ? min1 : min2;
    *max = max1 > max2 ? max1 : max2;
}

Tracing $A = {5, 4, 3, 8, 11, 2, 89, 23, 7}$: splitting down to pairs and singles gives sub-results $(\min,\max)$ of $(4,5)$, $(3,3)$ for the last singleton in an odd split, $(8,11)$, $(2,89)$, $(7,23)$ which combine level by level back up to the overall $(\min, \max) = (2, 89)$. The recurrence is $T(n) = 2T(n/2) + O(1)$, giving by the Master theorem ($a=2,b=2,f(n)=O(1)=O(n^{\log_2 2 - 1})$, case 1) $T(n) = \Theta(n)$, the same asymptotic order as the naive scan but with roughly $\frac{3n}{2}$ comparisons instead of $2n$, a constant-factor improvement.

What this unit covers

  • Searching Algorithms: Binary Search, Min-Max Finding and their Analysis
  • Sorting Algorithms: Merge Sort and Analysis, Quick Sort and Analysis (Best Case, Worst Case and Average Case), Heap Sort (Heapify, Build Heap and Heap Sort Algorithms and their Analysis), Randomized Quick sort and its Analysis
  • Order Statistics: Selection in Expected Linear Time, Selection in Worst Case Linear Time and their Analysis

Order Statistics

2082 ยท 10 marks

What is order statistics? Write and analyze the algorithm for randomized quick sort.[10]

--- Definition: The i-th order statistic of a set of n elements is the i-th smallest element in the set. In other words, if we sort the elements in ascending order, the element at position i is the i-th order statistic. Special Cases: - 1st order statistic = minimum element - n-th order statistic...

Open this answer on its own page โ†’

2079

Divide and Conquer Strategy and Worst-Case Linear Time Selection Algorithm

--- A divide and conquer algorithm recursively breaks down a problem into two or more sub-problems of the same or related type, until these become simple enough to be solved directly. The solutions to the sub-problems are then combined to give a solution to the original problem. Step Description ...

Open this answer on its own page โ†’

Searching Algorithms

2082 ยท 5 marks

Justify the worst case for binary search. Find the edit distance from the string "RELEVANT" to "ELEPHANT" using dynamic programming approach. [5+0]

Binary search operates on a sorted array. It compares the target with the middle element. If they are unequal, half the array is discarded, and the process repeats on the remaining half. $$T(n) = T\left(\frac{n}{2}\right) + O(1), \quad T(1) = O(1)$$ The worst case occurs when: - the target is not...

Open this answer on its own page โ†’

2080 ยท 5 marks

Write down nimmax algorithm and analyze its complexity. [5]

--- The Minimax algorithm is a recursive backtracking algorithm used in two-player zero-sum games (e.g., Chess, Tic-Tac-Toe). It determines the optimal move for a player assuming the opponent also plays optimally. - The MAX player tries to maximize the score. - The MIN player tries to minimize th...

Open this answer on its own page โ†’

Sorting Algorithms

2081 ยท 10 marks

What is the worst case of quick sort and how does randomize quick sort handle this problem? Sort the data ${-2, 4, -3, 6, 12, 10, 11, 13, 9}$ using quick sort. [10]

Show solved answer

Quick Sort: Worst Case, Randomized Version, and Sorting Example

Given

  • Array to sort: ${-2, 4, -3, 6, 12, 10, 11, 13, 9}$
  • Number of elements: $n = 9$
  • Marks: 10

Solution

Part A: Worst Case of Quick Sort

Quick Sort selects a pivot and partitions the array into elements smaller and larger than the pivot, then recursively sorts each part.

Worst case occurs when the pivot chosen at every step is the largest or smallest element, so the partition is maximally unbalanced: one side has $n-1$ elements, the other has $0$.

This happens (using first/last element as pivot) when the array is already sorted or reverse sorted.

Recurrence: $$T(n) = T(n-1) + T(0) + O(n) = T(n-1) + O(n)$$

Solving: $$T(n) = O(n) + O(n-1) + \dots + O(1) = O(n^2)$$

So worst case time complexity is $\mathbf{O(n^2)}$.

Part B: Randomized Quick Sort

Randomized Quick Sort picks the pivot randomly rather than always the first/last element.

RANDOMIZED-PARTITION(A, p, r):
    i = RANDOM(p, r)
    swap A[i] with A[r]
    return PARTITION(A, p, r)

RANDOMIZED-QUICKSORT(A, p, r):
    if p < r:
        q = RANDOMIZED-PARTITION(A, p, r)
        RANDOMIZED-QUICKSORT(A, p, q-1)
        RANDOMIZED-QUICKSORT(A, q+1, r)

How it helps: Since the pivot is chosen uniformly at random, no fixed input pattern (sorted/reverse sorted) can force worst-case behavior consistently. The probability of repeatedly hitting the worst split is extremely small. The expected running time becomes $O(n \log n)$ for any input, though the theoretical worst case remains $O(n^2)$ (with negligible probability).

Part C: Sorting Using Quick Sort (Lomuto, last element as pivot)

Array: $[-2, 4, -3, 6, 12, 10, 11, 13, 9]$

Step 1: pivot = 9

Elements $< 9$: $-2, 4, -3, 6$; elements $\ge 9$: $12, 10, 11, 13$

$$[-2, 4, -3, 6,; \boxed{9},; 12, 10, 11, 13]$$

Recurse on $[-2, 4, -3, 6]$ and $[12, 10, 11, 13]$.

Step 2: Left $[-2, 4, -3, 6]$, pivot = 6

All ($-2, 4, -3$) $< 6$: $$[-2, 4, -3,; \boxed{6}]$$ Recurse on $[-2, 4, -3]$.

Step 3: $[-2, 4, -3]$, pivot = -3

Both $-2, 4 \ge -3$: $$[\boxed{-3},; -2, 4]$$ Recurse on $[-2, 4]$.

Step 4: $[-2, 4]$, pivot = 4

$-2 < 4$: $$[-2,; \boxed{4}]$$ Sorted. Left portion โ†’ $[-3, -2, 4, 6]$

Step 5: Right $[12, 10, 11, 13]$, pivot = 13

$12, 10, 11 < 13$: $$[12, 10, 11,; \boxed{13}]$$ Recurse on $[12, 10, 11]$.

Step 6: $[12, 10, 11]$, pivot = 11

$10 < 11$, $12 \ge 11$: $$[10,; \boxed{11},; 12]$$ Left $[10]$ and right $[12]$ are single elements โ†’ sorted. Right portion โ†’ $[10, 11, 12, 13]$

Final Combination

$$\underbrace{[-3, -2, 4, 6]}{\text{left}} ;; \boxed{9} ;; \underbrace{[10, 11, 12, 13]}{\text{right}}$$

Final Sorted Array

$$\boxed{[-3, -2, 4, 6, 9, 10, 11, 12, 13]}$$

Open this answer on its own page โ†’

2080 ยท 10 marks

Discuss heapify operation with example. Write down its algorithm and analyze its time and space complexity.[10]

--- A heap is a complete binary tree stored as an array where: - Max-Heap property: Every parent node is greater than or equal to its children. - Min-Heap property: Every parent node is less than or equal to its children. For an array A with 0-based indexing, for any node at index i: - Left child...

Open this answer on its own page โ†’

2079 ยท 5 marks

Trace the quick sort algorithm for sorting the array $A[] = {15, 7, 6, 23, 18, 34, 25}$ and write its best and worst complexity. [5]

Show solved answer

Quick Sort - Trace, Best and Worst Complexity

Given

  • Array to sort: $A[] = {15, 7, 6, 23, 18, 34, 25}$, indices $0$ to $6$
  • $n = 7$ elements
  • Required: trace Quick Sort, and best and worst case time complexity
  • Pivot rule not specified. I use the first element as pivot (standard TU convention, Lomuto/Hoare style).

Solution

I use the Hoare-style partition with pivot = first element.

Initial: pivot = 15, range [0..6]

 15   7   6   23   18   34   25
  0   1   2    3    4    5    6
  • $i$ from left moves right while $A[i] < 15$: $A[1]=7<15$, $A[2]=6<15$, $A[3]=23\ge15$ โ†’ stop at $i=3$.
  • $j$ from right moves left while $A[j] > 15$: $A[6]=25>15$, $A[5]=34>15$, $A[4]=18>15$, $A[3]=23>15$, $A[2]=6\le15$ โ†’ stop at $j=2$.
  • $i > j$, so swap pivot $A[0]$ with $A[j]=A[2]$:

$${6, 7, \mathbf{15}, 23, 18, 34, 25}$$

Pivot 15 now at index 2. Left part = ${6,7}$, right part = ${23,18,34,25}$.

Left sub-array {6, 7}, pivot = 6, range [0..1]

  • $i$: $A[1]=7\ge6$ โ†’ stop at $i=1$.
  • $j$: $A[1]=7>6$ โ†’ move to $j=0$.
  • $i>j$, swap pivot $A[0]$ with $A[0]$ โ†’ no change.

$${\mathbf{6}, 7}$$

Pivot 6 at index 0; right part ${7}$ single element, sorted.

Right sub-array {23, 18, 34, 25}, pivot = 23, range [3..6]

 23   18   34   25
  3    4    5    6
  • $i$: $A[4]=18<23$, $A[5]=34\ge23$ โ†’ stop at $i=5$.
  • $j$: $A[6]=25>23$, $A[5]=34>23$, $A[4]=18\le23$ โ†’ stop at $j=4$.
  • $i>j$, swap pivot $A[3]$ with $A[4]$:

$${18, \mathbf{23}, 34, 25}$$

Pivot 23 at index 4. Left part ${18}$ sorted; right part ${34,25}$.

Sub-array {34, 25}, pivot = 34, range [5..6]

  • $i$: $A[6]=25<34$ โ†’ $i$ goes past range, stop at $i=6$ (or beyond).
  • $j$: $A[6]=25\le34$ โ†’ stop at $j=6$.
  • $i \ge j$, swap pivot $A[5]$ with $A[6]$:

$${25, \mathbf{34}}$$

Final Sorted Array

Index0123456
Value671518232534

$$A[] = {6, 7, 15, 18, 23, 25, 34}$$

Time Complexity

Best Case: $O(n \log n)$

  • Pivot splits the array into two nearly equal halves each time.
  • Recurrence: $T(n) = 2T(n/2) + O(n)$
  • Solution: $T(n) = O(n \log n)$

Worst Case: $O(n^2)$

  • Pivot is always the smallest or largest element (e.g., an already sorted array).
  • One partition has $n-1$ elements, the other $0$.
  • Recurrence: $T(n) = T(n-1) + O(n)$
  • Solution: $T(n) = O(n^2)$
CaseComplexity
Best$O(n \log n)$
Average$O(n \log n)$
Worst$O(n^2)$
Space$O(\log n)$ avg
Open this answer on its own page โ†’

2078 ยท 10 marks

Explain about the divide and conquer paradigm for algorithm design with suitable example. Write the Quick sort algorithm using randomized approach and explain its time complexity.[10]

--- Divide and Conquer is an algorithm design paradigm that solves a problem by: 1. Divide: Breaking the original problem into a number of smaller subproblems that are similar to the original problem. 2. Conquer: Solving the subproblems recursively. If the subproblem is small enough (base case), ...

Open this answer on its own page โ†’

2076 ยท 10 marks

Explain the divide and conquer paradigm from algorithm design with a suitable example. Write the Quick sort algorithm using a randomized approach and explain its time complexity.[10]

--- Divide and Conquer is a fundamental algorithm design paradigm that solves a problem by breaking it into smaller subproblems, solving each subproblem recursively, and then combining the results to produce the final solution. Step Description ------------------- Divide Break the original proble...

Open this answer on its own page โ†’

2076 ยท 5 marks

Trace heap sort algorithm for the following data: (2, 9, 3, 12, 15, 8, 11) [5]

  • Array (0-indexed): $A = [2, 9, 3, 12, 15, 8, 11]$, size $n = 7$ - Sort in ascending order using Max-Heap. Index relations: left child $= 2i+1$, right child $= 2i+2$. --- Last non-leaf node $= \lfloor n/2 \rfloor - 1 = 2$. Heapify from index 2 down to 0. Heapify index 2 (value 3): children 8 (id...
Open this answer on its own page โ†’