Skip to content

Commit e67541c

Browse files
shricubedtianyizheng02
authored andcommitted
Working binary insertion sort in Python (TheAlgorithms#8024)
1 parent f98ddf8 commit e67541c

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

Diff for: sorts/binary_insertion_sort.py

+61
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
"""
2+
This is a pure Python implementation of the binary insertion sort algorithm
3+
4+
For doctests run following command:
5+
python -m doctest -v binary_insertion_sort.py
6+
or
7+
python3 -m doctest -v binary_insertion_sort.py
8+
9+
For manual testing run:
10+
python binary_insertion_sort.py
11+
"""
12+
13+
14+
def binary_insertion_sort(collection: list) -> list:
15+
"""Pure implementation of the binary insertion sort algorithm in Python
16+
:param collection: some mutable ordered collection with heterogeneous
17+
comparable items inside
18+
:return: the same collection ordered by ascending
19+
20+
Examples:
21+
>>> binary_insertion_sort([0, 4, 1234, 4, 1])
22+
[0, 1, 4, 4, 1234]
23+
>>> binary_insertion_sort([]) == sorted([])
24+
True
25+
>>> binary_insertion_sort([-1, -2, -3]) == sorted([-1, -2, -3])
26+
True
27+
>>> lst = ['d', 'a', 'b', 'e', 'c']
28+
>>> binary_insertion_sort(lst) == sorted(lst)
29+
True
30+
>>> import random
31+
>>> collection = random.sample(range(-50, 50), 100)
32+
>>> binary_insertion_sort(collection) == sorted(collection)
33+
True
34+
>>> import string
35+
>>> collection = random.choices(string.ascii_letters + string.digits, k=100)
36+
>>> binary_insertion_sort(collection) == sorted(collection)
37+
True
38+
"""
39+
40+
n = len(collection)
41+
for i in range(1, n):
42+
val = collection[i]
43+
low = 0
44+
high = i - 1
45+
46+
while low <= high:
47+
mid = (low + high) // 2
48+
if val < collection[mid]:
49+
high = mid - 1
50+
else:
51+
low = mid + 1
52+
for j in range(i, low, -1):
53+
collection[j] = collection[j - 1]
54+
collection[low] = val
55+
return collection
56+
57+
58+
if __name__ == "__main__":
59+
user_input = input("Enter numbers separated by a comma:\n").strip()
60+
unsorted = [int(item) for item in user_input.split(",")]
61+
print(binary_insertion_sort(unsorted))

0 commit comments

Comments
 (0)