2 Iterative Algorithms

Design and Analysis of Algorithms · Unit 2 · 4 hrs

Iterative Algorithms

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

Iterative Algorithms in short

This unit works through non-recursive algorithms in three families: two simple numeric routines with their own recurrences, linear search, and the three quadratic sorting algorithms that form the baseline every faster sort is measured against.

Iterative Algorithms: notes

Basic Algorithms: Algorithm for GCD, Fibonacci Number and analysis of their time and space complexity

Euclid's algorithm for GCD rests on the identity $\gcd(m, n) = \gcd(n, m \bmod n)$, with $\gcd(m, 0) = m$.

int gcd(int m, int n) {
    while (n != 0) {
        int r = m % n;
        m = n;
        n = r;
    }
    return m;
}

Tracing $\gcd(24, 9)$: $24 \bmod 9 = 6$, so $(m,n) \to (9,6)$; then $9 \bmod 6 = 3$, so $(m,n) \to (6,3)$; then $6 \bmod 3 = 0$, so $(m,n) \to (3,0)$ and the loop stops, returning $3$. So $\gcd(24,9) = 3$. Since the loop body is $O(1)$ and the arguments at least halve roughly every two iterations (a consequence of the Fibonacci-growth lower bound on Euclid's algorithm), the loop runs $O(\log n)$ times, giving time complexity $O(\log n)$ and, since only three variables are kept regardless of the input, space complexity $O(1)$.

Fibonacci number by iteration keeps only the last two values instead of recomputing the whole tree of recursive calls:

int fibonacci(int n) {
    int first = 0, second = 1, temp;
    if (n == 1) return first;
    if (n == 2) return second;
    for (int i = 3; i <= n; i++) {
        temp = first + second;
        first = second;
        second = temp;
    }
    return temp;
}

with the convention that first is the 1st Fibonacci number ($0$) and second is the 2nd ($1$). Tracing $n = 5$: at $i=3$, $temp = 0+1=1$, so $(first,second) \to (1,1)$; at $i=4$, $temp=1+1=2$, so $(first,second)\to(1,2)$; at $i=5$, $temp=1+2=3$, so $(first,second)\to(2,3)$ and the loop ends. The 5th Fibonacci number is $3$. The loop runs $n-2$ times with $O(1)$ work per iteration, so the time complexity is $O(n)$, and since only four variables are used regardless of $n$, the space complexity is $O(1)$.

What this unit covers

  • Basic Algorithms: Algorithm for GCD, Fibonacci Number and analysis of their time and space complexity
  • Searching Algorithms: Sequential Search and its analysis
  • Sorting Algorithms: Bubble, Selection, and Insertion Sort and their Analysis

Sorting Algorithms

2082 · 5 marks

Find the best and worst case for Bubble sort. [5]

Bubble sort is the simplest sorting algorithm that works by repeatedly swapping adjacent elements if they are in the wrong order. A list with n elements requires n-1 passes for sorting. In each pass, element a[i] is compared with a[i+1] and swapped if they are not in proper order. --- --- The bes...

Open this answer on its own page →

2080 · 5 marks

Write down algorithm of insertion sort and analyze its time and space complexity. [5]

Insertion Sort works by picking each element and inserting it into its correct position among the already-sorted elements to its left. Steps: 1. Start with the array A of n elements. 2. Pick the element at position i (starting from i = 1). 3. Store it in a temporary variable temp = A[i]. 4. Compa...

Open this answer on its own page →

2078 · 5 marks

Write the algorithm for bubble sort and explain its time complexity. [5]

Idea: Repeatedly compare adjacent elements and swap them if they are in the wrong order. After each pass, the largest unsorted element "bubbles up" to its correct position. 1. Start from the beginning of the array. 2. Compare adjacent elements A[j] and A[j+1]. 3. If A[j] A[j+1], swap them; otherw...

Open this answer on its own page →

2076 · 5 marks

Write the algorithm for selection sort and explain its time and space complexity. [5]

Show solved answer

Selection Sort: Algorithm and Complexity Analysis

Definition

Selection Sort is a simple comparison-based sorting algorithm that works by repeatedly selecting the minimum element from the unsorted portion of the array and placing it at the correct position.


Algorithm (Steps)

  1. Start.
  2. Let array A have n elements (index 0 to n-1).
  3. For each position i from 0 to n-2:
    • Assume the current position i holds the minimum element (set min_index = i).
    • Scan the remaining unsorted portion (j from i+1 to n-1).
    • If A[j] < A[min_index], update min_index = j.
    • After scanning, swap A[i] with A[min_index].
  4. Repeat step 3 until the array is fully sorted.
  5. Stop.

Pseudocode

SelectionSort(A, n)
  for i = 0 to n-2
    min_index = i
    for j = i+1 to n-1
      if A[j] < A[min_index]
        min_index = j
    swap(A[i], A[min_index])

Example Trace

Sort: A = {64, 25, 12, 22, 11}

PassArray StateAction
111 25 12 22 64Min=11, swap with index 0
211 12 25 22 64Min=12, swap with index 1
311 12 22 25 64Min=22, swap with index 2
411 12 22 25 64Min=25, already in place
Done11 12 22 25 64Sorted

Time Complexity Analysis

Using the RAM model (each comparison and memory reference counts as 1 step):

  • The outer loop runs (n - 1) times.
  • For each pass i, the inner loop runs (n - 1 - i) times.
  • Total comparisons:

$$T(n) = (n-1) + (n-2) + (n-3) + \ldots + 1 = \frac{n(n-1)}{2}$$

CaseComplexityReason
Best CaseO(n²)Inner loop always runs fully; no early exit
Average CaseO(n²)Same number of comparisons regardless
Worst CaseO(n²)Same number of comparisons regardless

Unlike Bubble Sort (which has O(n) best case), Selection Sort always performs O(n²) comparisons because it must scan the entire unsorted portion to find the minimum, even if the array is already sorted.


Space Complexity Analysis

  • Selection Sort sorts the array in-place.
  • Only a constant number of extra variables are used: i, j, min_index, and a temporary swap variable.
  • The array A itself takes n memory references, but no additional array is needed.

$$\text{Space Complexity} = O(1)$$

This is consistent with the approach used in Bubble Sort (O(1) extra space) as noted in the course notes, since both are in-place sorting algorithms.


Summary Table

PropertyValue
Best Time ComplexityO(n²)
Average Time ComplexityO(n²)
Worst Time ComplexityO(n²)
Space ComplexityO(1)
Sorting TypeIn-place, Not stable
Open this answer on its own page →

Searching Algorithms

2082 · 5 marks

State the time and space complexity for sequential search. Write the rules for master theorem for finding asymptotic bounds. [5]

Show solved answer

Sequential Search: Time & Space Complexity + Master Theorem Rules


Sequential search (also called linear search) compares the search element with each element in the list one by one from the beginning.

Time Complexity

CaseConditionComplexity
Best CaseElement found at the first positionO(1)
Average CaseElement found somewhere in the middleO(n)
Worst CaseElement found at last position or not found at allO(n)

Since the loop executes at most n times, the overall time complexity is O(n).

Space Complexity

  • Sequential search only requires a fixed number of variables (search element, loop counter, etc.)
  • No extra data structure is used
  • Therefore, space complexity = O(1) (constant space)

Part 2: Master Theorem Rules for Asymptotic Bounds

The Master Theorem is used to find the time complexity of divide-and-conquer recursive algorithms whose recurrence relation is of the form:

$$T(n) = aT\left(\frac{n}{b}\right) + f(n)$$

Where:

  • a >= 1 : number of subproblems
  • b > 1 : factor by which input size is reduced
  • f(n) : cost of work done outside the recursive calls

Let p = log_b(a)


Rule 1: f(n) is polynomially smaller than n^p

If:

$$f(n) = O(n^{p - \epsilon}) \quad \text{for some } \epsilon > 0$$

Then:

$$T(n) = \Theta(n^p) = \Theta(n^{\log_b a})$$

The recursive work dominates.


Rule 2: f(n) is asymptotically equal to n^p

If:

$$f(n) = \Theta(n^p) = \Theta(n^{\log_b a})$$

Then:

$$T(n) = \Theta(n^p \log n) = \Theta(n^{\log_b a} \cdot \log n)$$

Both the recursive work and the combining work are equal, so a log factor is added.


Rule 3: f(n) is polynomially larger than n^p

If:

$$f(n) = \Omega(n^{p + \epsilon}) \quad \text{for some } \epsilon > 0$$

AND the regularity condition holds:

$$a \cdot f\left(\frac{n}{b}\right) \leq c \cdot f(n) \quad \text{for some } c < 1$$

Then:

$$T(n) = \Theta(f(n))$$

The combining work dominates.


Summary Table

ConditionResult
f(n) < n^(log_b a) polynomiallyT(n) = Theta(n^(log_b a))
f(n) = Theta(n^(log_b a))T(n) = Theta(n^(log_b a) * log n)
f(n) > n^(log_b a) polynomiallyT(n) = Theta(f(n))
Open this answer on its own page →

Basic Algorithms

2081 · 5 marks

Write an algorithm to find the $n^{th}$ fibonacci number with its time and space complexity. [5]

The Fibonacci sequence is defined as: - F(0) = 0 - F(1) = 1 - F(n) = F(n-1) + F(n-2) for n = 2 --- --- Iteration temp = first + second first second i --------------------------------------------------- Initial - 0 1 2 1 0 + 1 = 1 1 1 3 2 1 + 1 = 2 1 2 4 3 1 + 2 = 3 2 3 5 4 2 + 3 = 5 3 5 6 Result:...

Open this answer on its own page →

2079 · 5 marks

Explain the iterative algorithm to find the GCD of given two numbers and analyze its complexity. [5]

The GCD (Greatest Common Divisor) of two numbers is found using the iterative Euclidean algorithm based on the property that GCD(m, n) = GCD(n, m mod n). Steps: Pseudocode: --- Find GCD(48, 18): Step m n r = m mod n --------------------------- 1 48 18 48 mod 18 = 12 2 18 12 18 mod 12 = 6 3 12 6 1...

Open this answer on its own page →