Coders Packet

Bubble sort in Python

By Saitejasvi Prabhakar Poreddiwar

Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order.

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, these code is for Bubble sort.

Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.
Example: 
First Pass: 
5 1 4 2 3 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1. 
( 1 5 4 2 3 ) –>  ( 1 4 5 2 8 ), Swap since 5 > 4 
( 1 4 5 2 3 ) –>  ( 1 4 2 5 8 ), Swap since 5 > 2 
( 1 4 2 5 3 ) –> ( 1 4 2 3 5 ),  Swap since 5>3
Second Pass: 
1 4 2 3 5 ) –> ( 1 4 2 3 5 ) 
( 1 4 2 3 5 ) –> ( 1 2 4 3 5 ), Swap since 4 > 2 
( 1 2 4 3 5) –> ( 1 2 3 4 5 ) 
( 1 2 3 4 5 ) –>  ( 1 2 3 4 5 ) 
Now, the array is already sorted, but our algorithm does not know if it is completed. The algorithm needs one whole pass without any swap to know it is sorted.
Third Pass: 
( 1 2 3 4 5 ) –> ( 1 2 3 4 5 ) 

( 1 2 3 4 5 ) –> ( 1 2 3 4 5 ) 

( 1 2 3 4 5 ) –> ( 1 2 3 4 5 ) 

( 1 2 3 4 5 ) –> ( 1 2 3 4 5 ) 

Now below is our Python code:

# 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)

 

Download Complete Code

Comments

No comments yet