Skip to content

Commit 1869984

Browse files
committed
don't implement binary search again
1 parent 9592182 commit 1869984

File tree

1 file changed

+5
-11
lines changed

1 file changed

+5
-11
lines changed

sorts/binary_insertion_sort.py

+5-11
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
https://en.wikipedia.org/wiki/Insertion_sort#Variants
66
"""
77

8+
from bisect import bisect
9+
810

911
def binary_insertion_sort(collection: list) -> list:
1012
"""
@@ -36,18 +38,10 @@ def binary_insertion_sort(collection: list) -> list:
3638
n = len(collection)
3739
for i in range(1, n):
3840
value_to_insert = collection[i]
39-
low = 0
40-
high = i - 1
41-
42-
while low <= high:
43-
mid = (low + high) // 2
44-
if value_to_insert < collection[mid]:
45-
high = mid - 1
46-
else:
47-
low = mid + 1
48-
for j in range(i, low, -1):
41+
insertion_pos = bisect(collection[:i], value_to_insert)
42+
for j in range(i, insertion_pos, -1):
4943
collection[j] = collection[j - 1]
50-
collection[low] = value_to_insert
44+
collection[insertion_pos] = value_to_insert
5145
return collection
5246

5347

0 commit comments

Comments
 (0)