Bubble Sort - Python
Bubble Sort is one of the simplest sorting algorithms. It repeatedly compares adjacent elements in the list and swaps them if they are in the wrong order.
How Bubble Sort Works
- Compare each pair of adjacent elements.
- If the first element is greater than the second, swap them.
- After each full pass, the largest unsorted element "bubbles up" to its correct position at the end.
- Repeat this process for the remaining unsorted portion of the list.
- The algorithm stops early if no swaps occur in a pass, meaning the array is already sorted.
Python Implementation
def bubbleSort(arr):
n = len(arr)
for i in range(n):
swapped = False
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
swapped = True
if not swapped:
break
arr = [64, 34, 25, 12, 22, 11, 90]
bubbleSort(arr)
print(arr)
Output
[11, 12, 22, 25, 34, 64, 90]
Explanation:
- for i in range(n): Runs multiple passes; each pass positions the next largest element at the end.
- swapped = False: Flag to detect if any swap occurs in the current pass.
- for j in range(0, n - i - 1): Iterates through unsorted elements; range shrinks as the end becomes sorted.
- if arr[j] > arr[j + 1]: Checks for inversion between adjacent elements.
- arr[j], arr[j + 1] = arr[j + 1], arr[j]: Swaps elements in place using tuple unpacking.
- if not swapped: break, Stops early if no swaps occur, indicating the array is already sorted.