Skip to content

Instantly share code, notes, and snippets.

@5hirish
Last active April 10, 2016 11:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 5hirish/3e4ce4f1129437823b5d to your computer and use it in GitHub Desktop.
Save 5hirish/3e4ce4f1129437823b5d to your computer and use it in GitHub Desktop.
#!/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
Copy link
Author

5hirish commented Dec 17, 2015

Introduction to Algorithms by CLRS [2.1 Insertion Sort]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment