Challenge - 5 Problems
Bubble Sort Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediateOutput of Bubble Sort on a small list
What is the output of the following bubble sort code after sorting the list?
DSA Python
def bubble_sort(arr): n = len(arr) for i in range(n): for j in range(0, n-i-1): if arr[j] > arr[j+1]: arr[j], arr[j+1] = arr[j+1], arr[j] lst = [4, 2, 5, 1] bubble_sort(lst) print(lst)
Attempts:
2 left
💡 Hint
Remember bubble sort swaps adjacent elements if they are in the wrong order.
✗ Incorrect
Bubble sort compares pairs and swaps them to move the largest elements to the end step by step. After sorting, the list is in ascending order.
🧠 Conceptual
intermediateNumber of passes in Bubble Sort
For a list of length n, how many passes (outer loop iterations) does the bubble sort algorithm perform in the worst case?
Attempts:
2 left
💡 Hint
Think about how many times the largest element needs to bubble up to the end.
✗ Incorrect
Bubble sort performs n-1 passes because after n-1 passes, the list is guaranteed to be sorted.
🔧 Debug
advancedIdentify the error in this bubble sort code
What error will this bubble sort code produce when run?
DSA Python
def bubble_sort(arr): n = len(arr) for i in range(n): for j in range(n-i): if arr[j] > arr[j+1]: arr[j], arr[j+1] = arr[j+1], arr[j] lst = [3, 1, 2] bubble_sort(lst) print(lst)
Attempts:
2 left
💡 Hint
Check the inner loop range and the index used for accessing arr[j+1].
✗ Incorrect
The inner loop runs up to n-i, so arr[j+1] accesses an index outside the list on the last iteration causing IndexError.
❓ Predict Output
advancedOutput after partial bubble sort passes
What is the state of the list after the first pass (outer loop iteration) of bubble sort on this list?
DSA Python
lst = [5, 3, 4, 1, 2] n = len(lst) for j in range(n-1): if lst[j] > lst[j+1]: lst[j], lst[j+1] = lst[j+1], lst[j] print(lst)
Attempts:
2 left
💡 Hint
The largest element moves to the end after the first pass.
✗ Incorrect
After one pass, the largest number 5 bubbles to the last position, other elements are partially sorted.
🚀 Application
expertMinimum swaps in bubble sort for a nearly sorted list
Given the list [1, 2, 4, 3, 5], how many swaps will bubble sort perform to sort it completely?
DSA Python
def bubble_sort_count_swaps(arr): n = len(arr) swaps = 0 for i in range(n): for j in range(0, n-i-1): if arr[j] > arr[j+1]: arr[j], arr[j+1] = arr[j+1], arr[j] swaps += 1 return swaps lst = [1, 2, 4, 3, 5] print(bubble_sort_count_swaps(lst))
Attempts:
2 left
💡 Hint
4 and 3 are adjacent, so only one swap is needed.
✗ Incorrect
Only one swap is needed: swap 4 and 3 once, then the list is sorted with no more swaps.
