Bubble Sort
Return the ascending sequence by repeatedly fixing inverted neighbouring pairs.
EXECUTION LAB
Return the ascending sequence by repeatedly fixing inverted neighbouring pairs.
Input and constraints
- Use at most 32 integers. Each numeric input is between -1000 and 1000.
Code inspector
def solve(values, target): a = values.copy() end = (len(a) - 1) while (end > 0): changed = 0 i = 0 while (i < end): j = (i + 1) if (a[i] > a[j]): a[i], a[j] = a[j], a[i] changed = 1 i = (i + 1) if (changed == 0): break end = (end - 1) return aVisualizer
Step 1 of 1107i
12j
25
33end
Inspect the current state
Compare neighbouring positions 0 and 1.
Variable watch
i 0j 1end 3
Step explanation
Compare neighbouring positions 0 and 1.
comparisons 2reads 0writes 0swaps 0recursiveCalls 0
Educational simulation · O(n²) worst, O(n) best time · O(n) returned copy, O(1) auxiliary space
Worked explanation
In a line-up, taller neighbours step back until the tallest reaches the end.
Guided solution
The largest unplaced value reaches the end of each full pass.
O(n²) worst, O(n) best time · O(n) returned copy, O(1) auxiliary auxiliary space
Examples
Worked example · {"values":[7,2,5,3],"target":0} ⇒ [2,3,5,7]
Edge case 1 · {"values":[],"target":0} ⇒ []
Edge case 2 · {"values":[1,2,2],"target":0} ⇒ [1,2,2]
Progressive hints
Hint 1
In a line-up, taller neighbours step back until the tallest reaches the end.Hint 2
The largest unplaced value reaches the end of each full pass.Hint 3
Step through the worked example and inspect the highlighted variables before each update.Common mistake
An early-exit flag must be reset at the start of each pass.
Interview follow-up
What input gives this implementation a linear best case?