Skip to content

Commit bb9ca9e

Browse files
authored
Merge pull request #149 from kavienanj/sorting
Add Insertion Sort file #2
2 parents d066c40 + 7ce85d4 commit bb9ca9e

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed

Diff for: Algorithms/insertion_sort.py

+60
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
"""
2+
A pure Python implementation of the insertion sort algorithm
3+
4+
This algorithm sorts a collection by comparing adjacent elements.
5+
When it finds that order is not respected, it moves the element compared
6+
backward until the order is correct. It then goes back directly to the
7+
element's initial position resuming forward comparison.
8+
9+
For doctests run following command:
10+
python3 -m doctest -v insertion_sort.py
11+
12+
For manual testing run:
13+
python3 insertion_sort.py
14+
"""
15+
16+
17+
def insertion_sort(collection: list) -> list:
18+
"""A pure Python implementation of the insertion sort algorithm
19+
20+
:param collection: some mutable ordered collection with heterogeneous
21+
comparable items inside
22+
:return: the same collection ordered by ascending
23+
24+
Examples:
25+
>>> insertion_sort([0, 5, 3, 2, 2])
26+
[0, 2, 2, 3, 5]
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
41+
"""
42+
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
50+
return collection
51+
52+
53+
if __name__ == "__main__":
54+
from doctest import testmod
55+
56+
testmod()
57+
58+
user_input = input("Enter numbers separated by a comma:\n").strip()
59+
unsorted = [int(item) for item in user_input.split(",")]
60+
print(f"{insertion_sort(unsorted) = }")

0 commit comments

Comments
 (0)