Bubble Sort
This blog covers:
Introduction
Step-by-step working of Bubble Sort
Dry Run (Example)
Code Implementation (in Python)
Optimizations
Merits
Demerits
π Bubble Sort β A Step-by-Step Guide for Beginners
Sorting is one of the most fundamental operations in computer science, and Bubble Sort is often the first algorithm introduced to beginners. While it's not the most efficient for large datasets, it's incredibly valuable for learning how sorting algorithms work under the hood.
In this blog, weβll break down Bubble Sort step-by-step with examples, code, optimization tips, and its merits/demerits β all explained in simple language.
π What is Bubble Sort?
Bubble Sort is a simple comparison-based sorting algorithm. It repeatedly swaps adjacent elements if they are in the wrong order.
Imagine bubbling up the largest element to the top, just like bubbles rising to the surface of water β that's how the name "Bubble Sort" came into play.
π Step-by-Step Working of Bubble Sort
Letβs sort an array in ascending order using Bubble Sort:
Example:array = [5, 1, 4, 2, 8]
π Step 1: Outer Loop (Passes)
The algorithm goes through the array N-1 times (N = number of elements), where each pass places the next largest element in its correct position.
π Step 2: Inner Loop (Comparisons)
In each pass, it compares adjacent pairs (arr[j] and arr[j+1]):
If
array[j] > array[j+1], swap themElse, do nothing
β Step 3: Repeat Until Sorted
With each pass:
The largest unsorted element moves to its correct position at the end
Remaining unsorted elements are processed in the next pass
π§ Dry Run (Example)
Letβs dry-run array = [5, 1, 4, 2, 8] step-by-step:
π Pass 1:
Compare 5 and 1 β Swap β
[1, 5, 4, 2, 8]Compare 5 and 4 β Swap β
[1, 4, 5, 2, 8]Compare 5 and 2 β Swap β
[1, 4, 2, 5, 8]Compare 5 and 8 β No swap β
[1, 4, 2, 5, 8]
β Largest element (8) is in the correct position
π Pass 2:
Compare 1 and 4 β No swap
Compare 4 and 2 β Swap β
[1, 2, 4, 5, 8]Compare 4 and 5 β No swap
β Second largest (5) is now in place
π Pass 3:
Compare 1 and 2 β No swap
Compare 2 and 4 β No swap
β No swaps β array is now sorted!
π» Python Code β Bubble Sort
def bubble_sort(arr):
n = len(arr)
for i in range(n): # Outer loop
for j in range(0, n - i - 1): # Inner loop
if arr[j] > arr[j + 1]: # Compare and swap
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr
# Example usage
arr = [5, 1, 4, 2, 8]
sorted_arr = bubble_sort(arr)
print("Sorted array:", sorted_arr)
Output:
Sorted array: [1, 2, 4, 5, 8]
βοΈ Optimized Bubble Sort
The regular version does unnecessary passes even if the array is already sorted.
Letβs optimize it by adding a swapped flag. If no elements were swapped in a pass, we can exit early.
β Optimized Python Code:
def optimized_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: # No swap means array is sorted
break
return arr
# Example
arr = [1, 2, 3, 4, 5]
sorted_arr = optimized_bubble_sort(arr)
print("Sorted array:", sorted_arr)
β For already sorted or nearly sorted arrays, this is significantly faster.
β Merits of Bubble Sort
| Merit | Description |
| πΉ Simple | Easy to understand and implement |
| πΉ In-place | Doesnβt require extra memory |
| πΉ Stable | Maintains the relative order of equal elements |
| πΉ Educational | Great for teaching basic sorting logic |
β Demerits of Bubble Sort
| Demerit | Description |
| πΈ Inefficient | Time complexity is O(nΒ²) in worst and average case |
| πΈ Slow for large data | Not suitable for real-time or large-scale sorting |
| πΈ High number of swaps | More operations compared to efficient algorithms |
π Time and Space Complexity
| Case | Time Complexity |
| Best (sorted) | O(n) (with optimization) |
| Average | O(nΒ²) |
| Worst | O(nΒ²) |
| Space | O(1) (no extra space needed) |
π§Ύ Final Thoughts
Bubble Sort is not used in production systems, but it's still worth learning. Itβs like learning alphabets before writing sentences β fundamental, simple, and educational.
Once you're comfortable with Bubble Sort, move on to faster algorithms like:
Selection Sort
Insertion Sort
Merge Sort
Quick Sort