Software & Finance





Python - Insertion Sort





 

I have given python program to sort the numbers in ascending order using Insertion 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 Insertion Sort"
        arrNumbers = []
        i = 0
        j = 0
        k = 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):
           j = i
           while(j > 0):
              if( arrNumbers[j - 1] > arrNumbers[j]):
                 temp = arrNumbers[j]
                 arrNumbers[j] = arrNumbers[j - 1]
                 arrNumbers[j - 1] = temp
                 j -= 1
              else:
                 break
           print "After iteration: ", i
           for k in range (0, n):
              print arrNumbers[k], 
           print "/*** ", i + 1,  "numbers from the begining of the array are input and they are sorted ***/"
        
        print "The sorted array is: ", 
        for i in range (0, n):
           print arrNumbers[i], 
   
        #sample output
        #Python Program to sort the numbers using Insertion 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 5 3 2 1 /***  2 numbers from the begining of the array are input and they are sorted ***/
        #After iteration:  2
        #3 4 5 2 1 /***  3 numbers from the begining of the array are input and they are sorted ***/
        #After iteration:  3 
        #2 3 4 5 1 /***  4 numbers from the begining of the array are input and they are sorted ***/
        #After iteration:  4
        #1 2 3 4 5 /***  5 numbers from the begining of the array are input and they are sorted ***/
        #The sorted array is:  1 2 3 4 5