Skip to main content

Command Palette

Search for a command to run...

Bubble Sort

Published
β€’4 min readβ€’View as Markdown

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 them

  • Else, 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

MeritDescription
πŸ”Ή SimpleEasy to understand and implement
πŸ”Ή In-placeDoesn’t require extra memory
πŸ”Ή StableMaintains the relative order of equal elements
πŸ”Ή EducationalGreat for teaching basic sorting logic

❌ Demerits of Bubble Sort

DemeritDescription
πŸ”Έ InefficientTime complexity is O(nΒ²) in worst and average case
πŸ”Έ Slow for large dataNot suitable for real-time or large-scale sorting
πŸ”Έ High number of swapsMore operations compared to efficient algorithms

πŸ“Š Time and Space Complexity

CaseTime Complexity
Best (sorted)O(n) (with optimization)
AverageO(nΒ²)
WorstO(nΒ²)
SpaceO(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