Skip to content

Commit 43f9249

Browse files
Update insert sort (#2493)
* delete duplicate file update insert sort * rename * fixed error * using enumerate()
1 parent 6a39545 commit 43f9249

File tree

2 files changed

+25
-39
lines changed

2 files changed

+25
-39
lines changed

Diff for: sorts/i_sort.py

-21
This file was deleted.

Diff for: sorts/insertion_sort.py

+25-18
Original file line numberDiff line numberDiff line change
@@ -24,30 +24,37 @@ def insertion_sort(collection: list) -> list:
2424
Examples:
2525
>>> insertion_sort([0, 5, 3, 2, 2])
2626
[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
3341
"""
3442

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
4750
return collection
4851

4952

5053
if __name__ == "__main__":
54+
from doctest import testmod
55+
56+
testmod()
57+
5158
user_input = input("Enter numbers separated by a comma:\n").strip()
5259
unsorted = [int(item) for item in user_input.split(",")]
5360
print(f"{insertion_sort(unsorted) = }")

0 commit comments

Comments
 (0)