Python Program to Implement Bubble Sort

Python Program to Implement Bubble Sort

If you are just starting with Python programming, one of the fundamental concepts you need to understand is sorting algorithms. Sorting is a common task in programming, where we arrange items like numbers or words in a particular order. Among the many sorting algorithms, Bubble Sort is often the first one beginners learn because it is simple, easy to visualize, and a great way to understand how sorting works.

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

Bubble Sort works by repeatedly comparing adjacent elements in a list and swapping them if they are in the wrong order. Although it is not the fastest sorting method for large datasets, it is excellent for learning the logic behind sorting. You will often see Bubble Sort used in introductory programming courses, small projects, and scenarios where simplicity matters more than efficiency.

Program 1: Bubble Sort Using Loops

This program uses basic loops to implement Bubble Sort. It goes through the list multiple times, comparing adjacent numbers and swapping them if needed, until the list is fully sorted.

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]

    return arr


numbers = [64, 34, 25, 12, 22, 11, 90]

sorted_numbers = bubble_sort(numbers)

print("Sorted list:", sorted_numbers)

In this program, the outer loop controls how many passes we make through the list, while the inner loop compares and swaps elements. The n-i-1 part ensures we don’t check the elements already sorted at the end. Beginners can see how simple comparisons and swaps gradually arrange the numbers. This approach is very visual, making it easier to understand the concept of sorting step by step.

Program 2: Optimized Bubble Sort

Sometimes, the list might already be mostly sorted. In such cases, the standard Bubble Sort still goes through all iterations, which is not efficient. This optimized version stops early if no swaps were made in a pass, saving unnecessary comparisons.

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

    return arr


numbers = [10, 20, 30, 40, 50]

sorted_numbers = optimized_bubble_sort(numbers)

print("Sorted list:", sorted_numbers)

This version introduces a swapped flag to track whether any swaps occurred in a pass. If no swaps happen, the list is already sorted, and the algorithm can stop early. Beginners can appreciate this as a simple improvement that makes Bubble Sort smarter without complicating the logic.

Program 3: Bubble Sort Using Recursion

Bubble Sort can also be implemented recursively. Here, the function calls itself to sort the smaller parts of the list until everything is in order. This is a slightly advanced approach but helps in understanding how recursion works in algorithms.

def recursive_bubble_sort(arr, n=None):

    if n is None:
        n = len(arr)

    if n == 1:
        return arr

    for i in range(n-1):

        if arr[i] > arr[i+1]:
            arr[i], arr[i+1] = arr[i+1], arr[i]

    return recursive_bubble_sort(arr, n-1)


numbers = [5, 1, 4, 2, 8]

sorted_numbers = recursive_bubble_sort(numbers)

print("Sorted list:", sorted_numbers)

In this program, the largest element “bubbles” to the end with each recursive call. Each time, we reduce the effective size of the list by one and call the function again. This approach is useful for beginners who want to learn recursion and see how iterative logic can be converted into recursive logic.

Program 4: Bubble Sort in Descending Order

Sorting in descending order is just as simple as sorting in ascending order. By changing the comparison operator, we can reverse the sorting direction.

def bubble_sort_descending(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]

    return arr


numbers = [3, 7, 1, 9, 2]

print("Descending order:", bubble_sort_descending(numbers))

Here, we simply swap elements if the current element is smaller than the next. This version shows beginners how to manipulate comparison logic to achieve different sorting goals.

Program 5: Bubble Sort Using a Key Function

This approach allows us to sort elements based on a custom key, such as the absolute value. It introduces the idea of flexibility in sorting beyond simple numeric order.

def bubble_sort_key(arr, key=lambda x: x):

    n = len(arr)

    for i in range(n):

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

            if key(arr[j]) > key(arr[j + 1]):
                arr[j], arr[j + 1] = arr[j + 1], arr[j]

    return arr


numbers = [-10, 2, -30, 4, 5]

print("Sorted by absolute value:", bubble_sort_key(numbers, key=abs))

The key function provides a powerful way to customize sorting. Beginners can see how higher-order functions in Python make algorithms more flexible, allowing sorting based on any criteria they define.

Frequently Asked Questions (FAQ)

Sorting algorithms like Bubble Sort can raise a few common questions for beginners. Here are some answers to help you understand better.

Q1: Is Bubble Sort efficient for large arrays?
Bubble Sort is simple but not very efficient for large datasets because it has a time complexity of O(n²). For large arrays, algorithms like Quick Sort or Merge Sort are preferred.

Q2: Can Bubble Sort handle strings or other data types?
Yes, Bubble Sort can sort strings, lists, or objects as long as a comparison operation is defined.

Q3: Why use recursive Bubble Sort if loops work fine?
Recursive Bubble Sort is mostly educational. It helps beginners understand recursion and how problems can be broken down into smaller parts.

Q4: How does the optimized version improve performance?
By adding a swap check, the optimized version stops early if the array is already sorted, saving unnecessary iterations.

Q5: Can I sort by custom criteria?
Yes! Using a key function, you can sort elements based on absolute value, string length, or any property of objects.

Conclusion

Bubble Sort is a perfect starting point for learning sorting algorithms. Through simple loops, optimized checks, descending order, custom keys, and recursion, beginners can grasp both the basic and flexible aspects of sorting in Python. Practicing these variations strengthens your programming skills and prepares you for more advanced algorithms. Remember, the key is to experiment, modify, and understand each step—this hands-on approach makes learning programming enjoyable and effective.

Scroll to Top