Challenge - 5 Problems
Bubble Sort Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Bubble Sort on a small array
What is the output of the following C# code after performing bubble sort on the array?
DSA C#
int[] arr = {5, 3, 8, 4, 2}; for (int i = 0; i < arr.Length - 1; i++) { for (int j = 0; j < arr.Length - i - 1; j++) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } Console.WriteLine(string.Join(" -> ", arr) + " -> null");
Attempts:
2 left
💡 Hint
Remember bubble sort swaps adjacent elements if they are in the wrong order, pushing the largest to the end each pass.
✗ Incorrect
Bubble sort compares adjacent elements and swaps them if the left is greater than the right. After all passes, the array is sorted in ascending order.
🧠 Conceptual
intermediateNumber of passes in Bubble Sort
For an array of length n, how many passes (outer loop iterations) does the bubble sort algorithm perform in the worst case?
Attempts:
2 left
💡 Hint
Each pass places the largest unsorted element at the end, so one less pass than the array length is needed.
✗ Incorrect
Bubble sort requires n-1 passes to guarantee the array is sorted because each pass places one element in its correct position.
🔧 Debug
advancedIdentify the error in this Bubble Sort implementation
What error will this C# bubble sort code produce when run?
DSA C#
int[] arr = {4, 2, 7, 1}; for (int i = 0; i <= arr.Length - 1; i++) { for (int j = 0; j < arr.Length - i - 1; j++) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } Console.WriteLine(string.Join(" -> ", arr) + " -> null");
Attempts:
2 left
💡 Hint
Check the loop boundaries carefully to see if any index goes out of range.
✗ Incorrect
The outer loop runs from 0 to arr.Length - 1 inclusive, which is safe because inner loop limits prevent out-of-range access.
❓ Predict Output
advancedOutput after partial bubble sort passes
What is the state of the array after the first pass of bubble sort on this array?
DSA C#
int[] arr = {9, 7, 5, 3, 1}; for (int j = 0; j < arr.Length - 1; j++) { if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } Console.WriteLine(string.Join(" -> ", arr) + " -> null");
Attempts:
2 left
💡 Hint
One pass moves the largest element to the end by swapping adjacent pairs.
✗ Incorrect
After the first pass, the largest element 9 moves to the last position, and the rest shift left.
🧠 Conceptual
expertOptimization to stop Bubble Sort early
Which modification to the bubble sort algorithm can stop it early if the array is already sorted?
Attempts:
2 left
💡 Hint
If no swaps occur during a pass, the array is sorted and we can stop.
✗ Incorrect
A flag tracks if swaps happen; if none, the array is sorted and the algorithm stops early, improving efficiency.
