This notebook was prepared by [Donne Martin](http://donnemartin.com). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges).

Solution Notebook

Problem: Implement insertion sort.

Constraints

  • Is a naiive solution sufficient?
    • Yes

Test Cases

  • Empty input -> []
  • One element -> [element]
  • Two or more elements

Algorithm

Wikipedia's animation:

  • For each value index 1 to n - 1
    • Compare with all elements to the left of the current value to determine new insertion point
      • Hold current value in temp variable
      • Shift elements from new insertion point right
      • Insert value in temp variable
      • Break

Complexity:

  • Time: O(n^2) avarage, worst. O(1) best if input is already sorted.
  • Space: O(1), stable

Code


In [1]:
def insertion_sort(data):
    if len(data) < 2:
        return
    for r in range(1, len(data)):
        for l in range(0, r):
            if data[l] > data[r]:
                temp = data[r]
                data[l+1:r+1] = data[l:r]
                data[l] = temp
                break

Unit Test


In [2]:
%%writefile test_insertion_sort.py
from nose.tools import assert_equal


class TestInsertionSort(object):

    def test_insertion_sort(self):
        print('Empty input')
        data = []
        insertion_sort(data)
        assert_equal(data, [])

        print('One element')
        data = [5]
        insertion_sort(data)
        assert_equal(data, [5])

        print('Two or more elements')
        data = [5, 1, 7, 2, 6, -3, 5, 7, -1]
        insertion_sort(data)
        assert_equal(data, sorted(data))

        print('Success: test_insertion_sort')


def main():
    test = TestInsertionSort()
    test.test_insertion_sort()


if __name__ == '__main__':
    main()


Overwriting test_insertion_sort.py

In [3]:
%run -i test_insertion_sort.py


Empty input
One element
Two or more elements
Success: test_insertion_sort