Software & Finance





Python - Bubble Sort





 

I have given python program to sort the numbers in ascending order using Bubble Sort. We often using sorting algorithm to sort numbers and strings. Also we have many sorting algorithms. Look at the output to understand how algorithm works after each iteration.

This code is tested with Python version 2.6

 

        print "Python Program to sort the numbers using Bubble Sort"
        arrNumbers = []
        i = 0
        j = 0
        n = 0
        a = 0
        sum = 0
        temp = 0
        
        print "Total Numbers:", 
        n = input()
        
        for i in range (0, n):
           print "Enter", i + 1, "Number: ", 
           a = input()
           arrNumbers.append(a)
        
        for i in range (1, n):
           for j in range (0, n - i):
              if( arrNumbers[j] > arrNumbers[j + 1]):
                 temp = arrNumbers[j]
                 arrNumbers[j] = arrNumbers[j + 1]
                 arrNumbers[j + 1] = temp
           print "After iteration: ", i
           for k in range (0, n):
              print arrNumbers[k], 
           print "/*** ", i + 1,  "biggest number(s) is(are) pushed to the end of the array***/"
           
        print "The sorted array is: ", 
        for i in range (0, n):
           print arrNumbers[i], 

		#Python Program to sort the numbers using Bubble Sort
		#Total Numbers: 5
		#Enter 1 Number:  5
		#Enter 2 Number:  4
		#Enter 3 Number:  3
		#Enter 4 Number:  2
		#Enter 5 Number:  1
		#After iteration:  1
		#4 3 2 1 5 /***  2 biggest number(s) is(are) pushed to the end of the array***/
		#After iteration:  2
		#3 2 1 4 5 /***  3 biggest number(s) is(are) pushed to the end of the array***/
		#After iteration:  3
		#2 1 3 4 5 /***  4 biggest number(s) is(are) pushed to the end of the array***/
		#After iteration:  4
		#1 2 3 4 5 /***  5 biggest number(s) is(are) pushed to the end of the array***/
		#The sorted array is:  1 2 3 4 5