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

Challenge Notebook

Problem: Implement selection sort.

Constraints

  • Is a naiive solution sufficient (ie not stable, not based on a heap)?
    • Yes

Test Cases

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

Algorithm

Refer to the Solution Notebook. If you are stuck and need a hint, the solution notebook's algorithm discussion might be a good place to start.

Code


In [ ]:
def selection_sort(data, start=0):
    # TODO: Implement me (recursive)
    pass

In [ ]:
def selection_sort_iterative(data):
    # TODO: Implement me (iterative)
    pass

Unit Test

The following unit test is expected to fail until you solve the challenge.


In [ ]:
# %load test_selection_sort.py
from nose.tools import assert_equal


class TestSelectionSort(object):

    def test_selection_sort(self, func):
        print('Empty input')
        data = []
        func(data)
        assert_equal(data, [])

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

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

        print('Success: test_selection_sort\n')


def main():
    test = TestSelectionSort()
    test.test_selection_sort(selection_sort)
    try:
        test.test_selection_sort(selection_sort_iterative)
    except NameError:
        # Alternate solutions are only defined
        # in the solutions file
        pass


if __name__ == '__main__':
    main()

Solution Notebook

Review the Solution Notebook for a discussion on algorithms and code solutions.