- Notifications
You must be signed in to change notification settings - Fork 46.7k
/
Copy pathbinary_insertion_sort.py
66 lines (56 loc) · 1.95 KB
/
binary_insertion_sort.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
"""
This is a pure Python implementation of the binary insertion sort algorithm
For doctests run following command:
python -m doctest -v binary_insertion_sort.py
or
python3 -m doctest -v binary_insertion_sort.py
For manual testing run:
python binary_insertion_sort.py
"""
defbinary_insertion_sort(collection: list) ->list:
"""
Sorts a list using the binary insertion sort algorithm.
:param collection: A mutable ordered collection with comparable items.
:return: The same collection ordered in ascending order.
Examples:
>>> binary_insertion_sort([0, 4, 1234, 4, 1])
[0, 1, 4, 4, 1234]
>>> binary_insertion_sort([]) == sorted([])
True
>>> binary_insertion_sort([-1, -2, -3]) == sorted([-1, -2, -3])
True
>>> lst = ['d', 'a', 'b', 'e', 'c']
>>> binary_insertion_sort(lst) == sorted(lst)
True
>>> import random
>>> collection = random.sample(range(-50, 50), 100)
>>> binary_insertion_sort(collection) == sorted(collection)
True
>>> import string
>>> collection = random.choices(string.ascii_letters + string.digits, k=100)
>>> binary_insertion_sort(collection) == sorted(collection)
True
"""
n=len(collection)
foriinrange(1, n):
value_to_insert=collection[i]
low=0
high=i-1
whilelow<=high:
mid= (low+high) //2
ifvalue_to_insert<collection[mid]:
high=mid-1
else:
low=mid+1
forjinrange(i, low, -1):
collection[j] =collection[j-1]
collection[low] =value_to_insert
returncollection
if__name__=="__main":
user_input=input("Enter numbers separated by a comma:\n").strip()
try:
unsorted= [int(item) foriteminuser_input.split(",")]
exceptValueError:
print("Invalid input. Please enter valid integers separated by commas.")
raise
print(f"{binary_insertion_sort(unsorted) =}")