This post shows how to sort a list using Bubble Sort in Python — one of the simplest sorting algorithms, and a common one to be asked to implement by hand in interviews.
Bubble sort a list in Python:
Explanation:
Bubble sort repeatedly steps through the list, comparing adjacent elements and swapping them if they're in the wrong order. Each full pass "bubbles" the largest remaining element to the end, so after n passes, the list is fully sorted.
Python Program to Sort a List using Bubble Sort
numbers = [64, 25, 12, 22, 11]
n = len(numbers)
for i in range(n - 1):
for j in range(n - i - 1):
if numbers[j] > numbers[j + 1]:
numbers[j], numbers[j + 1] = numbers[j + 1], numbers[j]
print(f"Sorted list: {numbers}")
Output:
Sorted list: [11, 12, 22, 25, 64]
Bubble sort is simple but not efficient for large lists — see how it compares to other algorithms in our Interview Prep section.
