snippetpythonMinor
Insertion Sort Algorithm in Python
Viewed 0 times
insertionsortpythonalgorithm
Problem
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()Solution
One thing that can speed up insertion sort is to pull the partition value to the side and slide elements up into the vacancy until the correct location is found, then drop the partition value into that location. This eliminates one of the three assignments in the
The unit test shows a substantial speed improvement from doing this.
while loop:for p in range(1, len(seq)):
if seq[p] >= seq[p-1]:
continue
p_value = seq[p]
while p != 0 and p_value < seq[p-1]:
seq[p] = seq[p-1]
p -= 1
seq[p] = p_value
return seqThe unit test shows a substantial speed improvement from doing this.
Code Snippets
for p in range(1, len(seq)):
if seq[p] >= seq[p-1]:
continue
p_value = seq[p]
while p != 0 and p_value < seq[p-1]:
seq[p] = seq[p-1]
p -= 1
seq[p] = p_value
return seqContext
StackExchange Code Review Q#40809, answer score: 3
Revisions (0)
No revisions yet.