Bubble Sort Algorithm using Python

Hey!!! What’s up everyone?! I hope your week has been great! I have been working on tirelessly on my projects, so I am going to take a short break, and write up this article!

For today, I want to touch base on a classic algorithm that students have seen over the years, and it is called Bubble Sort Algorithm! Now, before I get started, there are obviously much better sorting algorithms are there, but for the sake of improving our critical thinking skills, Bubble Sort Algorithm is a good one!

Now, what is Bubble Sort Algorithm? It is the simplest sorting algorithm that works by swapping adjacent elements, until every element is sorted in the right order. I’m going to reference to the demonstration from GeeksforGeeks to help explain what the algorithm is about!

Now that you see how the algorithm works, let’s get to the code!

# bubble sort algorithm function
def bubbleSort(my_list):

    # first loop
    for i in range(len(my_list)):

        # second loop
        for j in range(0, len(my_list)-1): 

            # swapping logic
            if my_list[j] > my_list[j+1]:
                t = my_list[j]
                my_list[j] = my_list[j+1]
                my_list[j+1] = t

    # return the list
    return my_list

my_list = [4, 30, 22, 27, 41, 1, 5, 80]
print("Before sorted: ", end='')
print(my_list)
print("After sorted: ", end='')
print(bubbleSort(my_list))

The important thing to note about this algorithm is you need to think of how to go over different passes of the sequence, hence, you have to put the logic inside the nested loops. Another good way to solve this particular problem is you could also use recursive function, so if you want a challenge, solve it using recursion!

Anyways, I’m going to stop here for the day. If you have any question, don’t hesitate to ask!