Search This Blog

Thursday, June 11, 2009

Python Insertion Sort

#KEY: for each iteration, insert backward (if smaller), and swap forward

array = [9,4,1,2,5,3,6,8,7,0]
for index in range(len(array)):
current_min = array[index]
j = index
while j > 0 and array[j-1] < current_min:
array[j] = array[j-1]
j = j-1

array[j] = current_min

for a in array:
#note: , means print without a new line
print a,

No comments: