Skip to content

Commit dab4e64

Browse files
Bisma-Nadeemmpre-commit-ci[bot]cclauss
authored
Code enhancements in binary_insertion_sort.py (#10918)
* Code enhancements in binary_insertion_sort.py * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * Apply suggestions from code review --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: Christian Clauss <cclauss@me.com>
1 parent fd227d8 commit dab4e64

File tree

1 file changed

+15
-10
lines changed

1 file changed

+15
-10
lines changed

sorts/binary_insertion_sort.py

+15-10
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,11 @@
1212

1313

1414
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
15+
"""
16+
Sorts a list using the binary insertion sort algorithm.
17+
18+
:param collection: A mutable ordered collection with comparable items.
19+
:return: The same collection ordered in ascending order.
1920
2021
Examples:
2122
>>> binary_insertion_sort([0, 4, 1234, 4, 1])
@@ -39,23 +40,27 @@ def binary_insertion_sort(collection: list) -> list:
3940

4041
n = len(collection)
4142
for i in range(1, n):
42-
val = collection[i]
43+
value_to_insert = collection[i]
4344
low = 0
4445
high = i - 1
4546

4647
while low <= high:
4748
mid = (low + high) // 2
48-
if val < collection[mid]:
49+
if value_to_insert < collection[mid]:
4950
high = mid - 1
5051
else:
5152
low = mid + 1
5253
for j in range(i, low, -1):
5354
collection[j] = collection[j - 1]
54-
collection[low] = val
55+
collection[low] = value_to_insert
5556
return collection
5657

5758

58-
if __name__ == "__main__":
59+
if __name__ == "__main":
5960
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))
61+
try:
62+
unsorted = [int(item) for item in user_input.split(",")]
63+
except ValueError:
64+
print("Invalid input. Please enter valid integers separated by commas.")
65+
raise
66+
print(f"{binary_insertion_sort(unsorted) = }")

0 commit comments

Comments
 (0)