mirror of
https://github.com/TheAlgorithms/Python.git
synced 2024-11-23 21:11:08 +00:00
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>
This commit is contained in:
parent
fd227d8026
commit
dab4e64896
|
@ -12,10 +12,11 @@ python binary_insertion_sort.py
|
||||||
|
|
||||||
|
|
||||||
def binary_insertion_sort(collection: list) -> list:
|
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
|
Sorts a list using the binary insertion sort algorithm.
|
||||||
comparable items inside
|
|
||||||
:return: the same collection ordered by ascending
|
:param collection: A mutable ordered collection with comparable items.
|
||||||
|
:return: The same collection ordered in ascending order.
|
||||||
|
|
||||||
Examples:
|
Examples:
|
||||||
>>> binary_insertion_sort([0, 4, 1234, 4, 1])
|
>>> binary_insertion_sort([0, 4, 1234, 4, 1])
|
||||||
|
@ -39,23 +40,27 @@ def binary_insertion_sort(collection: list) -> list:
|
||||||
|
|
||||||
n = len(collection)
|
n = len(collection)
|
||||||
for i in range(1, n):
|
for i in range(1, n):
|
||||||
val = collection[i]
|
value_to_insert = collection[i]
|
||||||
low = 0
|
low = 0
|
||||||
high = i - 1
|
high = i - 1
|
||||||
|
|
||||||
while low <= high:
|
while low <= high:
|
||||||
mid = (low + high) // 2
|
mid = (low + high) // 2
|
||||||
if val < collection[mid]:
|
if value_to_insert < collection[mid]:
|
||||||
high = mid - 1
|
high = mid - 1
|
||||||
else:
|
else:
|
||||||
low = mid + 1
|
low = mid + 1
|
||||||
for j in range(i, low, -1):
|
for j in range(i, low, -1):
|
||||||
collection[j] = collection[j - 1]
|
collection[j] = collection[j - 1]
|
||||||
collection[low] = val
|
collection[low] = value_to_insert
|
||||||
return collection
|
return collection
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main":
|
||||||
user_input = input("Enter numbers separated by a comma:\n").strip()
|
user_input = input("Enter numbers separated by a comma:\n").strip()
|
||||||
unsorted = [int(item) for item in user_input.split(",")]
|
try:
|
||||||
print(binary_insertion_sort(unsorted))
|
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) = }")
|
||||||
|
|
Loading…
Reference in New Issue
Block a user