Skip to content

Instantly share code, notes, and snippets.

@5hirish 5hirish/insertion_sort.py
Last active Apr 10, 2016

Embed
What would you like to do?
#!/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

This comment has been minimized.

Copy link
Owner 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
You can’t perform that action at this time.