In this article we’ll try to understand bubble sort (also known as sinking sort) in Python. Aside from bubble sort there are many different sorting algorithms available such as Quick sort, Breadth-first search, Binary Search, Selection Sort etc… Out of all the searching algorithms bubble sort is one of the easiest sorting algorithm available.

The key technique used in bubble sort algorithm to sort a list is “Swapping”.

What is Swapping?

Swap values using a temporary variable
Swap values using a temporary variable

In programming, swapping is the process of exchanging the values of two variables. For example, let’s say we have two variables X and Y with 2 and 3 values respectively. 

After swapping these variables, X variable will contain the value 3 and Y will contain 2. 

Normally, swapping of two variables are done by using a third temporary variable. Here’s how you can swap values using a temporary variable.

Let’s say we have two variables “a” and “b”. Now we will take a third variable “c”. Now we will keep the value of “a” in “c” and then we will copy the value from “b” to “a” and finally we will copy the value from “c” to “b”.

Also Read: Python Tutorial For Beginners (Ultimate Guide)

How does bubble sort works?

Let’s say that we have the following values.

9 8 7 2 1 6 4

So what we’ll do is initially compare the first two values. In this case it’s 9 and 8.

Now we have to make sure that the smallest value (8) out of these come first.

So what we have to do is if first value is greater than the second value we need to swap.

In my case it’s greater. So 9 is > 8. After swapping the values our list is 8 9 7 2 1 6 4.

Once again we check. 9 > 2. So we swap them.

New list order is 8 7 2 9 1 6 4. Like vise we need to do this until we go to end of our list.

After that you will see that the largest value in our list which is “9” at the end of our list.

 8 7 2 1 6 4 9

Now we sorted one value in the list. But the other values are still unsorted. Therefore, we need to do the exact same steps again and again until we get the fully sorted list. That’s what you need to implement in to code. So let’s do the coding part…

def bubble_sort(list):
    for i in range(len(list)-1,0,-1):
        for j in range(i):
            if list[j]>list[j+1]:
                temp = list[j]
                list[j] = list[j+1]
                list[j+1] = temp

list = [9,8,7,2,1,6,4]
bubble sort python code
bubble sort python code

So that’s how bubble sort in Python works. Hope you learned something. Thanks for reading.

Write A Comment