1313python3 insertion_sort.py
1414"""
1515
16+ from collections .abc import MutableSequence
17+ from typing import Any , Protocol , TypeVar
1618
17- def insertion_sort (collection : list ) -> list :
19+
20+ class Comparable (Protocol ):
21+ def __lt__ (self , other : Any , / ) -> bool :
22+ ...
23+
24+
25+ T = TypeVar ("T" , bound = Comparable )
26+
27+
28+ def insertion_sort (collection : MutableSequence [T ]) -> MutableSequence [T ]:
1829 """A pure Python implementation of the insertion sort algorithm
1930
2031 :param collection: some mutable ordered collection with heterogeneous
@@ -40,13 +51,12 @@ def insertion_sort(collection: list) -> list:
4051 True
4152 """
4253
43- for insert_index , insert_value in enumerate ( collection [ 1 :] ):
44- temp_index = insert_index
45- while insert_index >= 0 and insert_value < collection [insert_index ]:
46- collection [insert_index + 1 ] = collection [insert_index ]
54+ for insert_index in range ( 1 , len ( collection ) ):
55+ insert_value = collection [ insert_index ]
56+ while insert_index > 0 and insert_value < collection [insert_index - 1 ]:
57+ collection [insert_index ] = collection [insert_index - 1 ]
4758 insert_index -= 1
48- if insert_index != temp_index :
49- collection [insert_index + 1 ] = insert_value
59+ collection [insert_index ] = insert_value
5060 return collection
5161
5262
0 commit comments