2076 10

CSC325 ยท 2076 ยท 5 marks

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

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

Design and Analysis of AlgorithmsChapter 2: Iterative AlgorithmsSorting Algorithms

Quick answer

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.

Selection Sort: Algorithm and Complexity Analysis

Definition


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

Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.