Thursday, April 17, 2014

Insertion sort in Python

Implementation of Insertion sort in Python:
def sort(array):

  for i, item in enumerate(array):
    j = i
    while j > 0 and array[j - 1] > item:
      array[j - 1], array[j] = item, array[j - 1]
      j -= 1

  return array
      

import random


for i in xrange(10000):
  n = random.randint(10, 1000)
  array = [random.randint(0, n) for j in xrange(n)]
  print "%s (%s)," % (i, n),
  assert sorted(array) == sort(array)


No comments:

Post a Comment