{{ message }}

Instantly share code, notes, and snippets.

# 5hirish/insertion_sort.py

Last active Apr 10, 2016
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
 #!/usr/bin/python import random list = [] for i in xrange(10): list.append(random.randrange(1,100,1)) #generate a list of ten random numbers between 1 and 100 print "The unsorted list : ",list for j in range(1,len(list)): key = list[j] #compare with next i = j - 1 print "comparing ",list[i]," and ",list[j] while i >= 0 and list[i] > key: #compare the key with the its left elements...if smaller swap list[i+1] = list[i] #swapping print "swapped ",list[i]," and ",key i = i - 1 #move left list[i+1] = key #swapping print "The sorted list Ascending : ",list print "\n" for i in xrange(10): list[i] = random.randrange(1,100,1) #generate a list of ten random numbers between 1 and 100 print "The unsorted list : ",list for j in range(1,len(list)): key = list[j] #compare with next i = j - 1 print "comparing ",list[i]," and ",list[j] while i >= 0 and list[i] < key: #compare the key with the its left elements...if greater swap list[i+1] = list[i] #swapping print "swapped ",list[i]," and ",key i = i - 1 #move left list[i+1] = key #swapping print "The sorted list Descending : ",list

### 5hirish commented Dec 17, 2015

 Introduction to Algorithms by CLRS [2.1 Insertion Sort]