Bubble Sort in Python: A Simple Sorting Algorithm

Introduction

When it comes to sorting a list or an array, there are numerous algorithms available, each with its own advantages and disadvantages. One of the simplest sorting algorithms is the Bubble Sort. Although not the most efficient algorithm for large datasets, it provides a clear understanding of the sorting process and is easy to implement in Python.

How does Bubble Sort work?

Bubble Sort works by repeatedly swapping adjacent elements if they are in the wrong order. The algorithm compares each pair of adjacent elements and swaps them if they are in the wrong order. This process is repeated until the entire list is sorted.

Visual Representation of Bubble Sort

The following steps will assist you in grasping the workings of bubble sort by providing an example with an array.

Iteration 1

The positions of the data in the array after the initial iteration, using the bubble sort algorithm.

Iteration 2

The positions of the data in the array after the second iteration, using the bubble sort algorithm.

Iteration 3

The positions of the data in the array after the final iteration (or the sorted array), using the bubble sort algorithm.

Implementing Bubble Sort in Python

To implement Bubble Sort in Python, we can start by defining a function that takes an unsorted list as an argument and returns the sorted list. Here’s an example implementation:


def bubble_sort(arr):
    n = len(arr)
    for i in range(n - 1):
        for j in range(n - i - 1):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
    return arr

Let’s break down the implementation step by step:

1. We start by defining the `bubble_sort` function that takes the `arr` (unsorted list) as an input.

2. We initialize the variable `n` with the length of the list `arr`. This will help us keep track of the number of elements in the list.

3. We use two nested loops to iterate through the list. The outer loop runs `n – 1` times because after each iteration, the largest element gets placed at the end of the list, so we can exclude it from the next iteration.

4. The inner loop compares adjacent elements and swaps them if they are in the wrong order. If `arr[j] > arr[j + 1]`, it means that the elements are out of order, and we swap them using a simultaneous assignment.

5. After the inner loop completes for a particular iteration of the outer loop, the largest element is in its correct position at the end of the list. This is why we reduce the range of the inner loop by `i` in each iteration.

6. Finally, we return the sorted list `arr` from the function.

Using the Bubble Sort function:

Once we have defined the bubble_sort function, we can use it to sort any unsorted list. Here’s an example:


unsorted_list = [7, 3, 1, 5, 2]
sorted_list = bubble_sort(unsorted_list)
print(sorted_list)

The output will be: `[1, 2, 3, 5, 7]`

Complexity Analysis of Bubble Sort

Time Complexity

Bubble Sort’s time complexity is determined by the number of comparisons and swaps it performs. In the worst-case scenario, where the input list is in reverse order, Bubble Sort requires the maximum number of comparisons and swaps. The number of comparisons can be calculated using the formula n*(n-1)/2, where n is the number of elements in the list. Similarly, the number of swaps will also be approximately n*(n-1)/2. Therefore, the worst-case time complexity of Bubble Sort is O(n^2).

In the best-case scenario, where the input list is already sorted, Bubble Sort still needs to make a pass through the entire list to confirm that it is sorted. In this case, the algorithm will perform n-1 comparisons and 0 swaps. Hence, the best-case time complexity of Bubble Sort is O(n).

The average-case time complexity of Bubble Sort is also O(n^2). This is because, on average, Bubble Sort requires a similar number of comparisons and swaps as in the worst-case scenario.

It’s important to note that Bubble Sort has a quadratic time complexity, which means that as the size of the input list grows, the time required to sort the list increases quadratically.

Space Complexity

Bubble Sort has a space complexity of O(1) since it only requires a constant amount of additional space to store temporary variables during the swapping process. Regardless of the input size, the amount of extra space used remains constant.

Advantages and Limitations

Bubble Sort is a simple algorithm to understand and implement. It has the following advantages:

1. Simplicity: The algorithm is easy to grasp and implement, making it a good choice for educational purposes or for small datasets.

2. Space Complexity: Bubble Sort has a space complexity of O(1) since it only requires a constant amount of additional space to store temporary variables.

However, Bubble Sort also has some limitations:

Time Complexity: Bubble Sort has an average and worst-case time complexity of O(n^2). This makes it inefficient for large datasets, as the number of comparisons and swaps grows exponentially.

Performance: Due to its inefficiency, Bubble Sort is not recommended for practical use when there are more efficient sorting algorithms available.

Conclusion

Bubble Sort is a simple and intuitive algorithm for sorting small datasets. While it may not be the most efficient algorithm, understanding how Bubble Sort works can provide a solid foundation for learning more advanced.

Share your love
Subhankar Rakshit
Subhankar Rakshit

Hey there! I’m Subhankar Rakshit, the brains behind PySeek. I’m a Post Graduate in Computer Science. PySeek is where I channel my love for Python programming and share it with the world through engaging and informative blogs.

Articles: 147