Bubble Sort: Data Structures and Algorithms - Python

·

2 min read

I have started learning data structure and algorithms recently. I have understood the importance of them. Well, this post will show you the program with comments that will help you what is happening in each line.

What does the below function do? You must know what a sort function does right? It solves the order of the list in a sequential way. Also, a sort function fixes the list which is actually abstracted from us. We do not know what happens under the hood until we find out. So the below function tells the process of sorting.

By the way, this sorting algorithm is one of the different ways of sorting. There are many more, easy, difficult, quick, and fastest without taking much space in your memory. Well, for this post. I will just post the code for Bubble sort.

# here we implement the bubble sort function. Example: How is a list sorted under the hood.

def bubble_sort(array):
        # loop through the range
        for i in range(len(array)):
            # loop until the range minus the last index
            for j in range(0,len(array) - i - 1):
                # checks index 1 greater than index 2 
                if array[j] > array[j+1]:
                    # copies the value to a new variable
                    temp = array[j]
                    # index 2 is placed in index 1
                    array[j] = array[j+1]
                    # index 1 is index 2
                    array[j+1] = temp



numbers = [99, 44, 6,2,1,5,63,87, 283,4,0]
bubble_sort(numbers)
print(numbers)

If you find it hard to understand, first understand how the execution should happen by watch one tutorial from YouTube or this link. Once the concept is clear, you will understand the code. The for loop does the magic.