Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Code enhancements in binary_insertion_sort.py #10918

Merged
merged 3 commits into from
Oct 24, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 15 additions & 10 deletions sorts/binary_insertion_sort.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,11 @@


def binary_insertion_sort(collection: list) -> list:
"""Pure implementation of the binary insertion sort algorithm in Python
:param collection: some mutable ordered collection with heterogeneous
comparable items inside
:return: the same collection ordered by ascending
"""
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])
Expand All @@ -39,23 +40,27 @@ def binary_insertion_sort(collection: list) -> list:

n = len(collection)
for i in range(1, n):
val = collection[i]
value_to_insert = collection[i]
low = 0
high = i - 1

while low <= high:
mid = (low + high) // 2
if val < collection[mid]:
if value_to_insert < collection[mid]:
high = mid - 1
else:
low = mid + 1
for j in range(i, low, -1):
collection[j] = collection[j - 1]
collection[low] = val
collection[low] = value_to_insert
return collection


if __name__ == "__main__":
if __name__ == "__main":
user_input = input("Enter numbers separated by a comma:\n").strip()
unsorted = [int(item) for item in user_input.split(",")]
print(binary_insertion_sort(unsorted))
try:
unsorted = [int(item) for item in user_input.split(",")]
except ValueError:
print("Invalid input. Please enter valid integers separated by commas.")
raise
print(f"{binary_insertion_sort(unsorted) = }")