@@ -24,30 +24,37 @@ def insertion_sort(collection: list) -> list:
24
24
Examples:
25
25
>>> insertion_sort([0, 5, 3, 2, 2])
26
26
[0, 2, 2, 3, 5]
27
-
28
- >>> insertion_sort([])
29
- []
30
-
31
- >>> insertion_sort([-2, -5, -45])
32
- [-45, -5, -2]
27
+ >>> insertion_sort([]) == sorted([])
28
+ True
29
+ >>> insertion_sort([-2, -5, -45]) == sorted([-2, -5, -45])
30
+ True
31
+ >>> insertion_sort(['d', 'a', 'b', 'e', 'c']) == sorted(['d', 'a', 'b', 'e', 'c'])
32
+ True
33
+ >>> import random
34
+ >>> collection = random.sample(range(-50, 50), 100)
35
+ >>> insertion_sort(collection) == sorted(collection)
36
+ True
37
+ >>> import string
38
+ >>> collection = random.choices(string.ascii_letters + string.digits, k=100)
39
+ >>> insertion_sort(collection) == sorted(collection)
40
+ True
33
41
"""
34
42
35
- for loop_index in range(1, len(collection)):
36
- insertion_index = loop_index
37
- while (
38
- insertion_index > 0
39
- and collection[insertion_index - 1] > collection[insertion_index]
40
- ):
41
- collection[insertion_index], collection[insertion_index - 1] = (
42
- collection[insertion_index - 1],
43
- collection[insertion_index],
44
- )
45
- insertion_index -= 1
46
-
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]
47
+ insert_index -= 1
48
+ if insert_index != temp_index:
49
+ collection[insert_index + 1] = insert_value
47
50
return collection
48
51
49
52
50
53
if __name__ == "__main__":
54
+ from doctest import testmod
55
+
56
+ testmod()
57
+
51
58
user_input = input("Enter numbers separated by a comma:\n").strip()
52
59
unsorted = [int(item) for item in user_input.split(",")]
53
60
print(f"{insertion_sort(unsorted) = }")
0 commit comments