Challenge - 5 Problems
Selection Sort Mastery
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 selection sort code on the array [3, 1, 4, 2]?
DSA C
void selectionSort(int arr[], int n) { for (int i = 0; i < n - 1; i++) { int min_idx = i; for (int j = i + 1; j < n; j++) { if (arr[j] < arr[min_idx]) { min_idx = j; } } int temp = arr[min_idx]; arr[min_idx] = arr[i]; arr[i] = temp; } } int main() { int arr[] = {3, 1, 4, 2}; int n = 4; selectionSort(arr, n); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } return 0; }
Attempts:
2 left
💡 Hint
Selection sort finds the smallest element and places it at the start, then repeats for the rest.
✗ Incorrect
Selection sort repeatedly selects the smallest element from the unsorted part and swaps it with the first unsorted element. After sorting, the array becomes 1 2 3 4.
🧠 Conceptual
intermediateNumber of swaps in selection sort
For an array of size n, how many swaps does selection sort perform in the worst case?
Attempts:
2 left
💡 Hint
Selection sort swaps only once per outer loop iteration.
✗ Incorrect
Selection sort performs exactly one swap per outer loop iteration, so total swaps are n - 1.
🔧 Debug
advancedIdentify the bug in selection sort implementation
What error will this selection sort code cause when sorting the array [5, 2, 9]?
DSA C
void selectionSort(int arr[], int n) { for (int i = 0; i < n; i++) { int min_idx = i; for (int j = i + 1; j < n; j++) { if (arr[j] < arr[min_idx]) { min_idx = j; } } int temp = arr[min_idx]; arr[min_idx] = arr[i]; arr[i] = temp; } }
Attempts:
2 left
💡 Hint
Check the inner loop condition carefully.
✗ Incorrect
The inner loop uses j <= n which accesses arr[n], out of array bounds causing runtime error.
❓ Predict Output
advancedOutput after partial selection sort pass
What is the state of the array after the first pass of selection sort on [7, 3, 5, 1]?
DSA C
void selectionSortPass(int arr[], int n) { int i = 0; int min_idx = i; for (int j = i + 1; j < n; j++) { if (arr[j] < arr[min_idx]) { min_idx = j; } } int temp = arr[min_idx]; arr[min_idx] = arr[i]; arr[i] = temp; } int main() { int arr[] = {7, 3, 5, 1}; int n = 4; selectionSortPass(arr, n); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } return 0; }
Attempts:
2 left
💡 Hint
Only the first smallest element is swapped with the first element.
✗ Incorrect
After the first pass, the smallest element 1 (at index 3) is swapped with 7 (at index 0), resulting in the array 1 3 5 7.
🧠 Conceptual
expertTime complexity of selection sort in all cases
What is the time complexity of selection sort in best, average, and worst cases?
Attempts:
2 left
💡 Hint
Selection sort always scans the entire unsorted part to find 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.
