Python Bubble Sort


Bubble sort is one of the simplest sorting algorithms you’ll learn in programming. Even though it’s not the fastest method, it plays an important role in understanding how sorting works and how elements move inside a list. The idea is very simple. You compare two elements at a time and swap them if they are out of order. By repeating this process, the largest elements “bubble” to the end of the list.

In this tutorial, you’ll learn how bubble sort works, how the swapping process happens, how the algorithm moves through the list step by step, and how to implement it in Python. You’ll also see real-world examples and learn where bubble sort is used in learning environments. This lesson builds your foundation for more efficient sorting algorithms like Quick Sort and Merge Sort.

What Is Bubble Sort?

Bubble sort is a sorting algorithm that goes through a list several times and compares each pair of adjacent items. If the current item is larger than the next one, they swap positions. This continues until the entire list becomes sorted.

The name “bubble” comes from the way larger values keep moving up toward the end, just like bubbles rising to the top.

How Bubble Sort Works Step by Step

Bubble sort works by making repeated passes through the list.

Consider this unsorted list:

[5, 2, 9, 1, 6]

Here’s what happens in the first pass:

  1. Compare 5 and 2 → swap → [2, 5, 9, 1, 6]

  2. Compare 5 and 9 → correct order → no swap

  3. Compare 9 and 1 → swap → [2, 5, 1, 9, 6]

  4. Compare 9 and 6 → swap → [2, 5, 1, 6, 9]

After the first full pass, the largest number (9) is now at the end.

The algorithm repeats this process until no swaps are needed.

Why Use Bubble Sort?

Bubble sort is useful for teaching because:

  • It is simple to understand

  • It shows how swapping works

  • It helps beginners learn algorithm flow

  • It is easy to implement in any language

  • It builds intuition for more complex sorting methods

Although bubble sort is slow for large lists, it still helps you understand sorting logic.

Bubble Sort Using a Loop

Here is the basic implementation:

def bubble_sort(data):
    n = len(data)

    for i in range(n):
        for j in range(0, n - i - 1):
            if data[j] > data[j + 1]:
                data[j], data[j + 1] = data[j + 1], data[j]

    return data

This version checks each pair and performs a swap when needed.

Optimized Bubble Sort

You can make bubble sort faster by stopping early if no swaps were made in a pass:

def bubble_sort_optimized(data):
    n = len(data)

    for i in range(n):
        swapped = False

        for j in range(0, n - i - 1):
            if data[j] > data[j + 1]:
                data[j], data[j + 1] = data[j + 1], data[j]
                swapped = True

        if not swapped:
            break

    return data

If the list becomes sorted early, the loop exits immediately.

Example Usage

numbers = [7, 3, 9, 2, 5]
sorted_list = bubble_sort(numbers)
print(sorted_list)

Output:

[2, 3, 5, 7, 9]

The result shows the list sorted in ascending order.

Time Complexity of Bubble Sort

Bubble sort has a slow runtime compared to other algorithms.

  • Best case: O(n)

  • Worst case: O(n²)

  • Average case: O(n²)

This means bubble sort is not suitable for large lists but works fine for teaching and small datasets.

When Bubble Sort Works Best

Bubble sort can be useful when:

  • The list is already almost sorted

  • You want to demonstrate algorithm behavior

  • You need a simple sorting method

  • Memory consumption must stay low

  • You work on very small datasets

Its simplicity makes it ideal for learning.

When Bubble Sort Is Not Suitable

Avoid bubble sort when:

  • Data is large

  • High performance is needed

  • There are frequent updates

  • Real-time processing is required

Faster algorithms like merge sort, quick sort, or insertion sort are better choices for large or real applications.

Real-Life Uses of Bubble Sort

Even though bubble sort is rarely used in professional systems, it appears in:

Classroom examples

Teachers use it to explain algorithm flow.

Visual sorting animations

You often see bubble sort in visual algorithm demos.

Small embedded devices

Simple devices sometimes use bubble sort because of low memory usage.

Debugging or teaching swaps

It helps show how elements move as conditions change.

Step-by-Step Example

List:

[4, 1, 3, 2]

Pass 1:

  • 4 and 1 → swap → [1, 4, 3, 2]

  • 4 and 3 → swap → [1, 3, 4, 2]

  • 4 and 2 → swap → [1, 3, 2, 4]

Pass 2:

  • 1 and 3 → no swap

  • 3 and 2 → swap → [1, 2, 3, 4]

The list becomes sorted after the second pass.

Practical Examples

Example 1: Basic sorting

print(bubble_sort([10, 4, 7, 2]))

Example 2: Sorting strings

items = ["pear", "apple", "banana"]
print(bubble_sort(items))

Example 3: Sorting floats

nums = [3.1, 1.2, 4.5, 2.8]
print(bubble_sort(nums))

Example 4: Early stop (optimized version)

print(bubble_sort_optimized([1, 2, 3, 4]))

Example 5: Reverse order sorting

print(bubble_sort([9, 7, 5, 3]))

Example 6: Sorting a list of tuples by first element

pairs = [(3,"a"), (1,"b"), (2,"c")]
print(bubble_sort(pairs))

Example 7: Sorting a list of characters

chars = ['d', 'a', 'c', 'b']
print(bubble_sort(chars))

Example 8: Sorting scores

scores = [58, 90, 72, 33]
print(bubble_sort(scores))

Example 9: Sorting names alphabetically

names = ["Liya", "Asha", "Mira"]
print(bubble_sort(names))

Example 10: Sorting small embedded device data

data = [3, 1, 2]
print(bubble_sort(data))

Summary of the Tutorial

Bubble sort is a simple sorting method that repeatedly compares and swaps adjacent elements until the list becomes sorted. You learned how the algorithm works, how swapping happens, how to write both standard and optimized versions in Python, and where the algorithm performs well. While it’s not the fastest sorting approach, it remains a great starting point in learning how sorting algorithms work.


Practice Questions

Q1. Write a Python program to sort the list [5, 3, 8, 4, 2] using bubble sort.

Q2. Write a Python program to sort a list in descending order using bubble sort.

Q3. Write a Python program to count and display how many swaps were made during the bubble sort process.

Q4. Write a Python program to accept a list of numbers from the user and sort it using bubble sort.

Q5. Write a Python program to add a check in bubble sort to exit early if the list is already sorted.

Q6. Write a Python program to sort a list of strings alphabetically using bubble sort.

Q7. Write a Python program to print the list after each pass in the bubble sort algorithm.

Q8. Write a Python program to find and print the total number of passes (iterations) made by bubble sort.

Q9. Write a Python program to modify bubble sort to stop after k passes (take k as user input).

Q10. Write a Python program to measure and display the time taken to bubble sort a list of 1000 random numbers.


Try a Short Quiz.

coding learning websites codepractice

No quizzes available.

Go Back Top