In this article we’ll try to understand the bubble sorting algorithm using 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 one available.

9 8 7 2 1 6 4

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

What is Swapping?

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”.

Swapping

How does bubble sort works?

Let’s say that we have the following values.

That’s what we are doing with the above list. So what we will do is we we’ll compare the first two values. In my case it’s 9 and 8. Now we have to make sure 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

Now what you have to do is go forward. Only thing we need to consider is if first value is greater than the second value, swap. Otherwise skip. Again in my case 9 > 7. So we have to swap them. After that list will look like this. 8 7 9 2 1 6 4

Also Read: Python Tutorials | Linear Search in Python

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

So that me we sorted one value in the list. But the other values are still not sorted. 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(list)
print(list)
Bubble Sort in Python

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *