Permalink
Browse files

Added insertion sort

  • Loading branch information...
0 parents commit 49609ccc54266acbdd1a4f6fd19af31eae9d2c11 @nryoung committed Aug 21, 2012
2 .gitignore
@@ -0,0 +1,2 @@
+*.pyc
+algo_venv/
0 README.rst
No changes.
0 algorithms/__init__.py
No changes.
0 algorithms/sorting/__init__.py
No changes.
12 algorithms/sorting/bubble_sort.py
@@ -0,0 +1,12 @@
+""" Implementation of Bubble Sort. """
+
+def sort(seq):
+
+ for x in seq:
+ temp = 0
+ for n in range(1, len(seq)):
+ temp = seq[n]
+ if seq[n] < seq[n-1]:
+ seq[n] = seq[n-1]
+ seq[n-1] = temp
+ return seq
11 algorithms/sorting/insertion_sort.py
@@ -0,0 +1,11 @@
+""" Implementation of Insertion Sort """
+
+def sort(seq):
+ for n in range(1, len(seq)):
+ item = seq[n]
+ hole = n
+ while hole > 0 and seq[ hole - 1] > item:
+ seq[hole] = seq[hole - 1]
+ hole = hole - 1
+ seq[hole] = item
+ return seq
16 algorithms/sorting/selection_sort.py
@@ -0,0 +1,16 @@
+""" Implementation of Selection Sort. """
+
+def sort(seq):
+
+ for i in range(0, len(seq)):
+ minat = i
+ minum = seq[i]
+ for j in range(i+1, len(seq)):
+ if minum > seq[j]:
+ minat = j
+ minum = seq[j]
+ temp = seq[i]
+ seq[i] = seq[minat]
+ seq[minat] = temp
+
+ return seq
0 algorithms/tests/__init__.py
No changes.
36 algorithms/tests/test_sorting.py
@@ -0,0 +1,36 @@
+import random
+import unittest
+from ..sorting import bubble_sort, selection_sort, insertion_sort
+
+class TestBubbleSort(unittest.TestCase):
+ """
+ Tests Bubble sort on a small range from 0-9
+ """
+ def test_bubblesort(self):
+ self.seq = range(10)
+ random.shuffle(self.seq)
+ rv = bubble_sort.sort(self.seq)
+ self.assertIs(self.seq[0], 0)
+ self.assertIs(self.seq[-1], 9)
+
+class TestSelectionSort(unittest.TestCase):
+ """
+ Tests Selection sort on a small range from 0-9
+ """
+ def test_selectionsort(self):
+ self.seq = range(10)
+ random.shuffle(self.seq)
+ rv = selection_sort.sort(self.seq)
+ self.assertIs(self.seq[0], 0)
+ self.assertIs(self.seq[-1], 9)
+
+class TestInsertionSort(unittest.TestCase):
+ """
+ Tests Insertion sort on a small range from 0-9
+ """
+ def test_selectionsort(self):
+ self.seq = range(10)
+ random.shuffle(self.seq)
+ rv = insertion_sort.sort(self.seq)
+ self.assertIs(self.seq[0], 0)
+ self.assertIs(self.seq[-1], 9)
4 run_tests.py
@@ -0,0 +1,4 @@
+import nose
+
+if __name__ == '__main__':
+ nose.main()

0 comments on commit 49609cc

Please sign in to comment.