Selection Sort Algorithm in DSA Rust - Time & Space Complexity
We want to understand how the time needed to sort a list using selection sort changes as the list gets bigger.
How does the number of steps grow when the input size increases?
Analyze the time complexity of the following code snippet.
fn selection_sort(arr: &mut [i32]) {
let n = arr.len();
for i in 0..n {
let mut min_index = i;
for j in (i + 1)..n {
if arr[j] < arr[min_index] {
min_index = j;
}
}
arr.swap(i, min_index);
}
}
This code sorts an array by repeatedly finding the smallest element from the unsorted part and swapping it to the front.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The inner loop compares elements to find the minimum.
- How many times: The outer loop runs n times, and for each outer loop, the inner loop runs fewer times, roughly n, n-1, n-2, ... down to 1.
As the list size grows, the number of comparisons grows roughly by the square of the size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 45 comparisons |
| 100 | About 4,950 comparisons |
| 1000 | About 499,500 comparisons |
Pattern observation: When input size doubles, operations roughly quadruple, showing a square growth pattern.
Time Complexity: O(n²)
This means the time needed grows roughly with the square of the input size, so doubling the list size makes the work about four times bigger.
[X] Wrong: "Selection sort is fast because it only swaps once per outer loop."
[OK] Correct: While it swaps less, the main cost is in comparing elements many times, which still takes a lot of time as the list grows.
Understanding selection sort's time complexity helps you appreciate why more efficient sorting methods are used in real projects, and shows you can analyze how algorithms behave as data grows.
"What if we changed the inner loop to stop early when the list is already sorted? How would the time complexity change?"
Practice
Selection Sort Algorithm?Solution
Step 1: Understand selection sort process
Selection sort finds the smallest element in the unsorted part and swaps it with the first unsorted element.Step 2: Compare with options
Repeatedly find the smallest element and move it to the front matches this description exactly, others describe different sorting methods.Final Answer:
Repeatedly find the smallest element and move it to the front -> Option AQuick Check:
Selection sort = find smallest and swap [OK]
- Confusing selection sort with bubble sort
- Thinking it divides list into halves
- Mixing it up with insertion sort
a[i] and a[min_index] in a vector a?Solution
Step 1: Recall Rust vector swap method
Rust vectors have a method calledswapthat takes two indices and swaps their elements.Step 2: Match syntax with options
a.swap(i, min_index); usesa.swap(i, min_index);which is correct. Others are invalid Rust syntax or methods.Final Answer:
a.swap(i, min_index); -> Option DQuick Check:
Rust vector swap method = a.swap(i, j) [OK]
- Trying to swap elements directly with assignment
- Using non-existent swap_elements method
- Using Python-style tuple swap syntax
vec![3, 1, 4, 2]?Solution
Step 1: Perform selection sort step-by-step
Initial vector: [3, 1, 4, 2] - Find smallest (1), swap with first element: [1, 3, 4, 2] - Find smallest in remaining (3,4,2) is 2, swap with second element: [1, 2, 4, 3] - Find smallest in last two (4,3) is 3, swap with third element: [1, 2, 3, 4]Step 2: Confirm final sorted vector
The vector is sorted ascending: [1, 2, 3, 4]Final Answer:
[1, 2, 3, 4] -> Option CQuick Check:
Selection sort output = sorted ascending [OK]
- Confusing selection sort with reverse sorting
- Stopping after first swap
- Not swapping correctly
fn selection_sort(a: &mut Vec<i32>) {
let n = a.len();
for i in 0..=n {
let mut min_index = i;
for j in i+1..n {
if a[j] < a[min_index] {
min_index = j;
}
}
a.swap(i, min_index);
}
}Solution
Step 1: Analyze loop ranges
The outer loop runs from 0 to n inclusive, meaning it runs n+1 times. But the last element does not need to be checked because it will already be sorted.Step 2: Correct loop range for outer loop
The outer loop should run from 0 to n-1 to avoid unnecessary iteration and potential out-of-bound errors.Final Answer:
The outer loop should run until n-1, not n -> Option BQuick Check:
Outer loop range = 0..n-1 [OK]
- Running outer loop one step too far
- Starting inner loop incorrectly
- Misunderstanding swap method existence
Solution
Step 1: Understand partial sorting requirement
We only want the first 3 smallest elements sorted at the front, so we only need to find and place the smallest element 3 times.Step 2: Modify selection sort outer loop
By running the outer loop 3 times, selection sort will place the 3 smallest elements in order at the front, leaving the rest unsorted.Final Answer:
Run the outer loop only 3 times instead of full length -> Option AQuick Check:
Partial sort = limit outer loop iterations [OK]
- Modifying inner loop instead of outer loop
- Sorting entire vector unnecessarily
- Mixing sorting algorithms incorrectly
Ready to prove it?
Pass the test and this pattern moves unknown
