Implementing basic sorting algorithms to learn them, and coding, better. Criticisms/ critiques welcome. Also possible optimizations.
import unittest import random def insertion_sort(seq): """Accepts a mutable sequence, utilizes insertion sort algorithm to sort in place. Returns an ordered list""" #marks point between ordered sublist & unordered list partition = 1 while partition < len(seq): temp = partition #while temp not in correct pos in sublist, decrement pos while temp != 0 and seq[temp] < seq[temp-1]: seq[temp], seq[temp-1] = seq[temp-1], seq[temp] temp -= 1 partition += 1 return seq class test_insertionsort(unittest.TestCase): def test_insertionsort(self): """Test insertion_sort()""" seq = [random.randrange(0, 1000) for _ in range(1000)] self.assertEqual(insertion_sort(seq), sorted(seq)) if __name__ == '__main__': unittest.main()
seq.pop
andseq.insert
is not really in the spirit of the exercise. These methods hide significant details of what the algorithm is doing. To really understand what is going on, you should try to implement it using only list assignment.\$\endgroup\$