13
13
python3 insertion_sort.py
14
14
"""
15
15
16
+ from collections .abc import MutableSequence
17
+ from typing import Any , Protocol , TypeVar
16
18
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 ]:
18
29
"""A pure Python implementation of the insertion sort algorithm
19
30
20
31
:param collection: some mutable ordered collection with heterogeneous
@@ -40,13 +51,12 @@ def insertion_sort(collection: list) -> list:
40
51
True
41
52
"""
42
53
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 ]
47
58
insert_index -= 1
48
- if insert_index != temp_index :
49
- collection [insert_index + 1 ] = insert_value
59
+ collection [insert_index ] = insert_value
50
60
return collection
51
61
52
62
0 commit comments