Bubble sort in Python
Bubble sort walks through the list again and again, swapping neighbours that are in the wrong order, so the largest values bubble up to the end one pass at a time.
The arrow keys step through it. Edit the code to try your own input.
How it works
- Compare each pair of neighbours,
nums[j]andnums[j + 1], from left to right. - If the left one is bigger, swap them. After one full pass the largest value has reached the end.
- Each pass can stop one place earlier (
n - 1 - i), because the end of the list is already sorted. - If a whole pass makes no swap, the list is sorted and the loop stops early.
What to watch
- Watch
jsweep to the right while the biggest bar travels with it to the end of each pass. - Watch
swapped: the last pass finds nothing to swap, sobreakends the sort early.
The code
def bubble_sort(nums): n = len(nums) for i in range(n - 1): swapped = False for j in range(n - 1 - i): if nums[j] > nums[j + 1]: nums[j], nums[j + 1] = nums[j + 1], nums[j] swapped = True if not swapped: break return nums data = [5, 1, 4, 2, 8] print(bubble_sort(data))
Output
[1, 2, 4, 5, 8]
Open it in the editor · Python Program for Bubble Sort, explained