What Is Bubble Sort? Working and Examples

When you start learning about algorithms and sorting techniques, one name that frequently pops up is Bubble Sort. It is often one of the first sorting algorithms taught to beginners, not because it is the fastest, but because it helps you understand the logic behind sorting in a very visual and intuitive way.

In this article, we will explore what Bubble Sort is, how it works, its algorithmic structure, some code examples, and the pros and cons you should be aware of.

What Is Bubble Sort? Working and Examples

 This will help you build a strong foundation in programming logic and get ready for coding interviews. Whether you are a student, an aspiring software engineer, or someone trying to understand how computers organize data, this guide will make the concept clear and simple.

If you are just starting with coding or looking to revise core topics, consider checking out the Data Structures and Algorithms course at Uncodemy. It provides practical explanations, real life projects, and expert mentorship to boost your coding journey.

What Is Bubble Sort?

Bubble Sort is a simple sorting algorithm that compares adjacent elements in a list and swaps them if they are in the wrong order. This process continues repeatedly until the entire list is sorted.

Imagine you are holding a bunch of playing cards and you want to arrange them in ascending order. You begin by looking at the first two cards, swap them if needed, then move to the next two, and so on. This process is repeated multiple times until all the cards are in the correct order. That is exactly how Bubble Sort works, and just like bubbles in water, the largest values rise to the top of the list with each pass.

Why Is It Called Bubble Sort?

The term “Bubble” refers to the way larger elements gradually rise to the top of the list after each pass through the array. Smaller values sink to the bottom while larger ones float upward, just like bubbles in a glass of soda. Although it is not the most efficient method, it is one of the easiest to understand, especially for those new to algorithms.

Understanding Bubble Sort with a Simple Example

Let us say we have the following list of numbers:

Copy Code

csharp

CopyEdit

[5, 3, 8, 4, 2]

We want to sort them in ascending order using Bubble Sort. Here is how it works step by step:

First Pass

  • 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]
     

The largest number 8 is now at the end. One bubble has reached the surface.

Second Pass

  • 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]
     
  • 8 is already in place
     

Third Pass

  • Compare 3 and 4 → no swap
     
  • Compare 4 and 2 → swap → [3, 2, 4, 5, 8]
     
  • Compare 4 and 5 → no swap
     
  • Last two elements are already in order
     

Fourth Pass

  • Compare 3 and 2 → swap → [2, 3, 4, 5, 8]
     
  • Rest is already sorted
     

Now the list is completely sorted in ascending order.

The Bubble Sort Algorithm

Here is the general logic of Bubble Sort written in simple language:

  1. Start from the first element
     
  2. Compare the current element with the next element
     
  3. If the current element is greater, swap them
     
  4. Move to the next pair and repeat
     
  5. Continue this process for every element in the list
     
  6. Repeat the entire pass as many times as needed until the list is sorted

Bubble Sort Pseudocode

Copy Code

css

CopyEdit

for i from 0 to length of array - 1

    for j from 0 to length of array - i - 1

        if array[j] > array[j + 1]

            swap array[j] and array[j + 1]

This double loop structure ensures the list is sorted after each full pass, with the largest remaining unsorted element moving to the end in each round.

Bubble Sort in C

Here is an example of how Bubble Sort is written in the C programming language:

Copy Code

c

CopyEdit

#include <stdio.h>



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

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

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

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

                int temp = arr[j];

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

                arr[j + 1] = temp;

            }

        }

    }

}



void printArray(int arr[], int size) {

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

        printf("%d ", arr[i]);

    printf("\n");

}



int main() {

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

    int size = sizeof(data) / sizeof(data[0]);



    bubbleSort(data, size);

    printf("Sorted array: ");

    printArray(data, size);



    return 0;

}

This simple code shows how Bubble Sort is implemented and how arrays are sorted by repeatedly comparing and swapping elements.

Bubble Sort in Python

For those who prefer Python, here is how it looks:

Copy Code

python

CopyEdit

def bubble_sort(arr):

    n = len(arr)

    for i in range(n):

        for j in range(0, n - i - 1):

            if arr[j] > arr[j + 1]:

                arr[j], arr[j + 1] = arr[j + 1], arr[j]



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

bubble_sort(data)

print("Sorted array:", data)

This version is compact and easier to read, thanks to Python’s clean syntax.

Optimized Bubble Sort

The basic Bubble Sort always performs n passes even if the list is already sorted. This can be optimized using a simple trick. If no swaps happen in a particular pass, it means the list is already sorted, and we can exit early.

Copy Code

python

CopyEdit

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:

            break

Adding this swapped flag makes the algorithm smarter and helps reduce unnecessary operations.

Time and Space Complexity

Time Complexity

  • Worst Case: O(n²) — when the list is in reverse order
     
  • Average Case: O(n²)
     
  • Best Case: O(n) — when the list is already sorted and optimized version is used
     

Space Complexity

  • O(1) — no extra space is used, making it an in place sorting algorithm

When Should You Use Bubble Sort?

Bubble Sort is not used in production level systems or competitive programming where performance matters. However, it is still a great educational tool. Here are some situations where it can be helpful:

  • Learning sorting concepts for the first time
     
  • Teaching programming to school or college students
     
  • Understanding how nested loops and comparisons work
     
  • Solving very small datasets where performance is not critical

Advantages of Bubble Sort

  • Simple to understand and implement
     
  • No additional memory is required
     
  • Helpful for educational purposes
     
  • Can be optimized for nearly sorted lists

Disadvantages of Bubble Sort

  • Very slow on large datasets
     
  • Not practical for real world applications
     
  • Has better alternatives like Merge Sort, Quick Sort, and Insertion Sort

Real Life Analogy

Imagine standing in a queue with people randomly arranged by height. You go from person to person and if the one in front is taller than the one behind, you ask them to switch places. You repeat this process again and again until the shortest person is at the front and the tallest person is at the back. That is Bubble Sort in action, just with people instead of numbers.

Learn Sorting Algorithms with Uncodemy

If you found Bubble Sort interesting and want to explore more efficient algorithms like Merge Sort, Quick Sort, or Heap Sort, the Data Structures and Algorithms course from Uncodemy is a great place to start. You will get access to expert instructors, real life examples, and interactive coding problems that help you master sorting and searching in a fun and structured way.

Whether you are preparing for interviews at top tech companies or improving your college grades, learning these concepts from a trusted platform can save you hours of confusion and give you a clear advantage.

Final Thoughts

Bubble Sort may not be the fastest algorithm, but it holds a special place in the world of programming. It is often the first step in the journey of learning how computers sort and compare data. Its simplicity, clarity, and step by step nature make it perfect for beginners who want to develop logical thinking.

By practicing Bubble Sort and understanding how each pass affects the array, you strengthen your fundamentals and become ready to tackle more complex algorithms. So next time you sort a list of numbers, try visualizing the bubbles rising to the top.

And remember, coding is not just about writing efficient code. It is also about understanding how things work under the hood. If you want to dive deeper, explore Uncodemy’s learning paths and start building your algorithmic intuition today.

Placed Students

Our Clients

Partners

...

Uncodemy Learning Platform

Uncodemy Free Premium Features

Popular Courses