Insertion sort (in Python)

March 24, 2009

# Insertion sort
# Date: Tuesday, March 24, 2009

print 'Insertion sort\n'
print 'How many numbers would you like to enter: '
num = input()

print 'Please enter ' + str(num) + ' numbers'

numbers = []
for i in range(num):
    numbers += [input()]

for j in range(1, num):
    key = numbers[j]
    i = j-1
    # Keep shifting elements to the right until the right position is found
    while numbers[i] > key and i >= 0:
        numbers[i+1] = numbers[i]
        i = i - 1
    numbers[i+1] = key
    print(numbers)
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s