Challenge - 5 Problems
Insertion Sort Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Insertion Sort on a small array
What is the output of the following C code after sorting the array using insertion sort?
DSA C
void insertionSort(int arr[], int n) { int i, key, j; for (i = 1; i < n; i++) { key = arr[i]; j = i - 1; while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; } } int main() { int arr[] = {5, 2, 9, 1}; int n = 4; insertionSort(arr, n); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } return 0; }
Attempts:
2 left
💡 Hint
Insertion sort places each element in its correct position by comparing it with elements before it.
✗ Incorrect
The insertion sort algorithm sorts the array by taking each element and inserting it into the sorted part on the left. The final sorted array is 1 2 5 9.
🧠 Conceptual
intermediateNumber of comparisons in insertion sort
For an array of size 5 sorted in descending order, how many comparisons does insertion sort make in the worst case?
Attempts:
2 left
💡 Hint
Worst case is when every new element is smaller than all sorted elements before it.
✗ Incorrect
In worst case, insertion sort makes comparisons equal to the sum of first (n-1) natural numbers: 1+2+3+4=10 comparisons.
🔧 Debug
advancedIdentify the bug in this insertion sort code
What error will this code produce when run?
DSA C
void insertionSort(int arr[], int n) { int i, key, j; for (i = 1; i <= n; i++) { key = arr[i]; j = i - 1; while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; } }
Attempts:
2 left
💡 Hint
Check the loop condition for i carefully.
✗ Incorrect
The for loop runs with i <= n, which accesses arr[n], out of bounds since valid indices are 0 to n-1.
❓ Predict Output
advancedOutput after partial insertion sort steps
What is the state of the array after the first two iterations of the insertion sort on this array?
DSA C
int arr[] = {4, 3, 2, 1}; int n = 4; // After two iterations of insertion sort
Attempts:
2 left
💡 Hint
Insertion sort sorts one element at a time from left to right.
✗ Incorrect
After first iteration: 3 4 2 1; after second iteration: 2 3 4 1.
🧠 Conceptual
expertTime complexity of insertion sort on nearly sorted array
What is the time complexity of insertion sort when the input array is already sorted except for one element at the end?
Attempts:
2 left
💡 Hint
Insertion sort moves elements only when needed.
✗ Incorrect
When only one element is out of place at the end, insertion sort shifts elements once, resulting in linear time O(n).
