What Is Bubble Sort? Working and Examples Explained Simply

When learning about sorting algorithms, Bubble Sort is often the first algorithm students encounter. Why? Because it’s simple to understand, easy to implement, and offers a perfect introduction to the logic behind sorting.

In this blog, we’ll break down what Bubble Sort is, how it works, its step-by-step process, examples, code in C++ and Python, real-life use cases, and its advantages and limitations. Whether you’re a beginner or preparing for coding interviews, this guide will simplify the concept of Bubble Sort for you.

What Is Bubble Sort

We’ll also share a relevant course from Uncodemy to help you strengthen your data structures and algorithms skills.

📘 What Is Bubble Sort?

Bubble Sort is a simple comparison-based sorting algorithm that repeatedly steps through a list, compares adjacent elements, and swaps them if they are in the wrong order.

This process is repeated until the list becomes sorted.

The name “Bubble Sort” comes from the way larger elements "bubble up" to the end of the list, like bubbles rising in water.

🔧 How Does Bubble Sort Work?

Let’s break down the process:

1. Compare the first two elements.
 

2. If the first is greater than the second, swap them.
 

3. Move to the next pair and repeat step 2.
 

4. Continue until the end of the list.
 

5. Repeat the entire process for the unsorted part of the list until no swaps are needed.

Each pass moves the largest element to its correct position at the end.

🔄 Step-by-Step Example of Bubble Sort

Let’s sort this list in ascending order using Bubble Sort:

Input:
 [5, 3, 8, 4, 2]

Pass 1:

  • Compare 5 and 3 → swap → [3, 5, 8, 4, 2]
     
  • Compare 5 and 8 → no swap
     
  • Compare 8 and 4 → swap → [3, 5, 4, 8, 2]
     
  • Compare 8 and 2 → swap → [3, 5, 4, 2, 8]
     

End of Pass 1: Largest element (8) is at the rightmost position.

Pass 2:

  • Compare 3 and 5 → no swap
     
  • Compare 5 and 4 → swap → [3, 4, 5, 2, 8]
     
  • Compare 5 and 2 → swap → [3, 4, 2, 5, 8]
     

Pass 3:

  • Compare 3 and 4 → no swap
     
  • Compare 4 and 2 → swap → [3, 2, 4, 5, 8]
     

Pass 4:

  • Compare 3 and 2 → swap → [2, 3, 4, 5, 8]
     

Sorted!

🧠 Dry Run Helps Build Logic

Bubble sort is a great exercise to practice comparison logic, loop nesting, and array manipulation. It teaches beginners how to track variable changes and spot inefficiencies in brute-force algorithms.

💻 Bubble Sort Code Examples

🔹 Bubble Sort in C++

cpp

CopyEdit

Copy Code

#include <iostream>

using namespace std;

void bubbleSort(int arr[], int n) {

    for(int i = 0; i < n - 1; i++) {

        bool swapped = false;

        for(int j = 0; j < n - i - 1; j++) {

            if(arr[j] > arr[j + 1]) {

                // Swap

                int temp = arr[j];

                arr[j] = arr[j + 1];

                arr[j + 1] = temp;

                swapped = true;

            }

        }

        if(!swapped) break; // Optimized break

    }

}

int main() {

    int arr[] = {5, 3, 8, 4, 2};

    int n = sizeof(arr)/sizeof(arr[0]);

    bubbleSort(arr, n);

    cout << "Sorted array: ";

    for(int i = 0; i < n; i++)

        cout << arr[i] << " ";

}

🔹 Bubble Sort in Python

python

CopyEdit

Copy Code

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  # Optimization

arr = [5, 3, 8, 4, 2]

bubble_sort(arr)

print("Sorted array:", arr)

⚙️ Time and Space Complexity

CaseTime Complexity
Best Case (Already Sorted)O(n)
Average CaseO(n²)
Worst Case (Reversed)O(n²)

Space Complexity: O(1) (in-place sorting)

✔️ Advantages of Bubble Sort

  • Easy to understand and implement
     
  • Requires only a few lines of code
     
  • Good for small or nearly sorted datasets
     
  • In-place sorting (no extra space needed)
     

❌ Disadvantages of Bubble Sort

  • Very slow for large datasets
     
  • Inefficient compared to modern algorithms (like Merge Sort or Quick Sort)
     
  • High time complexity O(n²) in average and worst cases
     

📦 Where Is Bubble Sort Used?

While rarely used in production systems, Bubble Sort is used:

  • In educational settings to teach sorting concepts
     
  • In small-scale embedded systems
     
  • When data is nearly sorted
     
  • As a foundation to understand more efficient sorting algorithms
     

🔎 Comparison: Bubble Sort vs Other Algorithms

AlgorithmTime Complexity (Average)SpaceStable
Bubble SortO(n²)O(1)Yes
Selection SortO(n²)O(1)No
Insertion SortO(n²)O(1)Yes
Merge SortO(n log n)O(n)Yes
Quick SortO(n log n)O(log n)No

Bubble sort loses performance-wise but wins in simplicity and clarity.

🧑‍🏫 Bubble Sort in Interviews

Typical interview questions:

  • “Write a program to implement Bubble Sort.”
     
  • “What is the best and worst case time complexity of Bubble Sort?”
     
  • “How can you optimize Bubble Sort?”
     

📌 Knowing how to explain the process clearly is just as important as writing the code.

🧪 Practice Problems Based on Bubble Sort

Here are some beginner-friendly problems you can try:

1. Sort an array of integers in descending order using Bubble Sort.

2. Count the number of swaps required to sort a list.

3. Modify Bubble Sort to stop after ‘k’ passes.

4. Implement Bubble Sort on a list of strings alphabetically.

These help you understand variations and real-world constraints of the algorithm.

🎓 Learn Sorting Algorithms with Uncodemy

If you want to dive deeper into sorting, searching, and algorithms, we recommend:

👉 Data Structures and Algorithms Course by Uncodemy

Why This Course?

  • Explains algorithms like Bubble, Merge, Quick, Heap with animations
     
  • Includes real coding interview challenges
     
  • Taught in beginner-friendly language (Hindi & English available)
     
  • Hands-on implementation in Python, Java, and C++
     
  • Lifetime access and certification available
     

Uncodemy’s DSA course helps you go from theory to code to confidence.

✅ Conclusion: Is Bubble Sort Worth Learning?

Absolutely! While Bubble Sort may not be used in high-performance systems, it’s still one of the most important learning tools for beginners.

It teaches you:

  • Loop control
     
  • Comparison logic
     
  • Array manipulation
     
  • The importance of algorithm efficiency
     

As you build your programming foundation, mastering Bubble Sort will open the door to understanding more advanced algorithms like Quick Sort, Merge Sort, and Heap Sort.

💡 Quick Recap: Key Points

  • Bubble Sort compares and swaps adjacent elements until sorted
     
  • Works best on small or nearly sorted datasets
     
  • Time complexity is O(n²); space complexity is O(1)
     
  • It’s a great beginner exercise for building logic
     
  • You can implement it in any language (C++, Python, Java)
     
  • Optimized versions can stop early if the array is already sorted

Placed Students

Our Clients

Partners

...

Uncodemy Learning Platform

Uncodemy Free Premium Features

Popular Courses