Python BUBBLE SORT Tutorial

 

In this tutorial page we will look at how to implement the  Bubble sort algorithm using Python.

How does the Bubble Sort work in Python?

The bubble sort is probbaly the simplest  way to sort an array of numbers ,  it works on the principal of looping through an array one element at a time, it compares two adjacent numbers. If the one on the left is greater than the one on the right, then we swap them around and  set a flag to indicate that something has changed. 

 At the end of the loop we check the flag and if it is set (something changed) we repeat the process. We do this in a WHILE loop until the flag is not set, this only happens when the list is finally sorted.

 

#function to sort our array 
def bubbleSort():

    #flag to indicate if anything changes,1 means sorted 
    sorted=0

    #loop through the numbers until sorted =1 (sorted is true)
    while sorted==0:
        #set sorted to true (gets set to zero if anthing changes)
        sorted=1
        #loop through all the numbers
        for a in range(0,len(mylist)-1,1):
            #if the left number is bigger then swap them around
            if mylist[a] > mylist[a+1]:
               temp=mylist[a]
               mylist[a]=mylist[a+1]
               mylist[a+1]=temp
               #set sorted to false to indicate a change was made
               sorted=0
        
#------------------------------------------------------------
# function to show the usorted list of numbers
#------------------------------------------------------------
#function to show the array of unsorted numbers
def showlist():
    for a in range(0,len(mylist),1):
        print (mylist[a])

#------------------------------------------------------------
#The main program starts here!
#------------------------------------------------------------
#create our list we want to sort
mylist=[12,67,2,1,1,43,21]
#print unsorted list
showlist()
#sort the array when user presss a key 
userinput=input("Press a key to sort the array")
#call our function sort the list
bubbleSort()
#print unsorted list
showlist()