Bubble Sort Algorithm
Bubble Sort repeatedly steps through the array, compares adjacent elements, and swaps them if they are in the wrong order. Larger elements 'bubble' to the end of the array with each pass.
Algorithm Steps
- Compare each pair of adjacent elements from the start of the array.
- Swap them if the left element is greater than the right one.
- Repeat for the entire array; after each pass, the largest unsorted element settles at the end.
- Stop early if a pass completes with no swaps (array is already sorted).
def bubble_sort(arr):
n = len(arr)
for i in range(n - 1):
swapped = False
for j in range(n - 1 - i):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
swapped = True
if not swapped:
break
return arr
print(bubble_sort([5, 1, 4, 2, 8]))
Complexity
| Case | Time | Space |
|---|---|---|
| Best (already sorted, with flag) | O(n) | O(1) |
| Average | O(n²) | O(1) |
| Worst | O(n²) | O(1) |
Key Characteristics
- Stable sort — equal elements retain their relative order.
- Simple to implement, but inefficient for large datasets compared to Merge Sort or Quick Sort.
- Mainly used for teaching sorting concepts and for very small or nearly-sorted datasets.
Ready to master Data Structures & Algorithms?
Learn DSA hands-on with mentor-led sessions, real interview practice, and placement support.
.png)