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]
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)
- Start.
- Let array A have n elements (index 0 to n-1).
- 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], updatemin_index = j. - After scanning, swap
A[i]withA[min_index].
- Assume the current position i holds the minimum element (set
- Repeat step 3 until the array is fully sorted.
- 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}
| Pass | Array State | Action |
|---|---|---|
| 1 | 11 25 12 22 64 | Min=11, swap with index 0 |
| 2 | 11 12 25 22 64 | Min=12, swap with index 1 |
| 3 | 11 12 22 25 64 | Min=22, swap with index 2 |
| 4 | 11 12 22 25 64 | Min=25, already in place |
| Done | 11 12 22 25 64 | Sorted |
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}$$
| Case | Complexity | Reason |
|---|---|---|
| Best Case | O(nยฒ) | Inner loop always runs fully; no early exit |
| Average Case | O(nยฒ) | Same number of comparisons regardless |
| Worst Case | O(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
| Property | Value |
|---|---|
| Best Time Complexity | O(nยฒ) |
| Average Time Complexity | O(nยฒ) |
| Worst Time Complexity | O(nยฒ) |
| Space Complexity | O(1) |
| Sorting Type | In-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.