Last active
April 10, 2016 11:29
-
-
Save 5hirish/3e4ce4f1129437823b5d to your computer and use it in GitHub Desktop.
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Introduction to Algorithms by CLRS [2.1 Insertion Sort]