Bubble Sort is one of the simplest sorting algorithms: it repeatedly steps through the list, compares adjacent elements, and swaps them if they are out of order. Its name comes from how larger elements "bubble" to the end of the list over multiple iterations.
Bubble Sort is easy to understand and implement, making it a staple in algorithm education. It excels at sorting small or nearly-sorted datasets due to its adaptive nature—if a pass results in no swaps, the list is already sorted and the process can terminate early.
However, Bubble Sort is inefficient for large, random datasets. Its time complexity in the average and worst cases is quadratic—O(n²)—making it significantly slower than more advanced algorithms like QuickSort or Merge Sort.
Case | Time Complexity |
---|---|
Best (already sorted with optimization) | O(n) |
Average | O(n²) |
Worst | O(n²) |
# Python - optimized bubble sort
def bubble_sort(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
return arr