Challenge - 5 Problems
Selection Sort Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Selection Sort on a small array
What is the output of the following Rust code after performing selection sort on the array?
DSA Rust
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);
}
}
fn main() {
let mut data = [64, 25, 12, 22, 11];
selection_sort(&mut data);
println!("{:?}", data);
}Attempts:
2 left
💡 Hint
Selection sort finds the smallest element and places it at the start, then repeats for the rest.
✗ Incorrect
The selection sort algorithm repeatedly selects the smallest remaining element and swaps it to the front. After sorting, the array is in ascending order: [11, 12, 22, 25, 64].
🧠 Conceptual
intermediateNumber of swaps in selection sort
For an array of 5 elements, how many swaps does the selection sort algorithm perform in the worst case?
Attempts:
2 left
💡 Hint
Selection sort swaps only once per outer loop iteration if needed.
✗ Incorrect
Selection sort performs exactly n-1 swaps in the worst case, where n is the number of elements. For 5 elements, it performs 4 swaps.
🔧 Debug
advancedIdentify the bug in this selection sort implementation
What error does the following Rust code produce when run?
DSA Rust
fn selection_sort(arr: &mut [i32]) {
let n = arr.len();
for i in 0..n {
let mut min_index = i;
for j in i..n {
if arr[j] < arr[min_index] {
min_index = j;
}
}
arr.swap(i, min_index);
}
}
fn main() {
let mut data = [3, 1, 2];
selection_sort(&mut data);
println!("{:?}", data);
}Attempts:
2 left
💡 Hint
Check the inner loop range carefully.
✗ Incorrect
The inner loop starts at i, which includes the current element. This is valid and does not cause errors. The code runs correctly and outputs the sorted array.
❓ Predict Output
advancedSelection sort on a reversed array
What is the output of the following Rust code after sorting the reversed array?
DSA Rust
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);
}
}
fn main() {
let mut data = [5, 4, 3, 2, 1];
selection_sort(&mut data);
println!("{:?}", data);
}Attempts:
2 left
💡 Hint
Selection sort always sorts in ascending order.
✗ Incorrect
The reversed array is sorted into ascending order by selection sort, resulting in [1, 2, 3, 4, 5].
🧠 Conceptual
expertTime complexity of selection sort
What is the time complexity of selection sort in all cases (best, average, worst)?
Attempts:
2 left
💡 Hint
Selection sort always scans the entire unsorted part to find the minimum.
✗ Incorrect
Selection sort always performs n*(n-1)/2 comparisons regardless of input order, so time complexity is O(n^2) in all cases.
