Challenge - 5 Problems
Bubble Sort Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of Bubble Sort on a small array
What is the output of the following Go code after performing bubble sort on the array?
DSA Go
package main import "fmt" func bubbleSort(arr []int) { n := len(arr) for i := 0; i < n-1; i++ { for j := 0; j < n-i-1; j++ { if arr[j] > arr[j+1] { arr[j], arr[j+1] = arr[j+1], arr[j] } } } } func main() { arr := []int{5, 1, 4, 2, 8} bubbleSort(arr) fmt.Println(arr) }
Attempts:
2 left
💡 Hint
Bubble sort swaps adjacent elements if they are in the wrong order, repeatedly.
✗ Incorrect
The bubble sort algorithm compares adjacent elements and swaps them if the left element is greater than the right. After all passes, the array is sorted in ascending order.
🧠 Conceptual
intermediate1:00remaining
Number of passes in Bubble Sort
For an array of length n, how many passes does the bubble sort algorithm perform in the worst case?
Attempts:
2 left
💡 Hint
Each pass places the largest unsorted element at the end.
✗ Incorrect
Bubble sort requires n-1 passes to guarantee the array is sorted because each pass places one element in its correct position.
🔧 Debug
advanced2:00remaining
Identify the error in this Bubble Sort implementation
What error will this Go code produce when run?
DSA Go
package main import "fmt" func bubbleSort(arr []int) { n := len(arr) for i := 0; i < n; i++ { for j := 0; j < n-i-1; j++ { if arr[j] > arr[j+1] { arr[j], arr[j+1] = arr[j+1], arr[j] } } } } func main() { arr := []int{3, 2, 1} bubbleSort(arr) fmt.Println(arr) }
Attempts:
2 left
💡 Hint
Check the inner loop boundary conditions carefully.
✗ Incorrect
The inner loop runs until j < n-i-1, so arr[j+1] does not access out of range. The original code had j < n-i which caused the runtime error.
🚀 Application
advanced1:30remaining
Optimizing Bubble Sort to stop early
Which modification to the bubble sort algorithm allows it to stop early if the array is already sorted?
Attempts:
2 left
💡 Hint
If no swaps occur in a pass, the array is sorted.
✗ Incorrect
Adding a boolean flag to detect swaps lets the algorithm stop early, improving efficiency on nearly sorted arrays.
❓ Predict Output
expert2:30remaining
Output of Bubble Sort on a reversed array with duplicates
What is the output of the following Go code after bubble sort is applied?
DSA Go
package main import "fmt" func bubbleSort(arr []int) { n := len(arr) for i := 0; i < n-1; i++ { for j := 0; j < n-i-1; j++ { if arr[j] > arr[j+1] { arr[j], arr[j+1] = arr[j+1], arr[j] } } } } func main() { arr := []int{9, 7, 7, 5, 3, 3, 1} bubbleSort(arr) fmt.Println(arr) }
Attempts:
2 left
💡 Hint
Bubble sort sorts all elements including duplicates in ascending order.
✗ Incorrect
The bubble sort correctly sorts the array including duplicates, resulting in ascending order.