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
(collection: list)
| 12 | |
| 13 | |
| 14 | def binary_insertion_sort(collection: list) -> list: |
| 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. |
| 20 | |
| 21 | Examples: |
| 22 | >>> binary_insertion_sort([0, 4, 1234, 4, 1]) |
| 23 | [0, 1, 4, 4, 1234] |
| 24 | >>> binary_insertion_sort([]) == sorted([]) |
| 25 | True |
| 26 | >>> binary_insertion_sort([-1, -2, -3]) == sorted([-1, -2, -3]) |
| 27 | True |
| 28 | >>> lst = ['d', 'a', 'b', 'e', 'c'] |
| 29 | >>> binary_insertion_sort(lst) == sorted(lst) |
| 30 | True |
| 31 | >>> import random |
| 32 | >>> collection = random.sample(range(-50, 50), 100) |
| 33 | >>> binary_insertion_sort(collection) == sorted(collection) |
| 34 | True |
| 35 | >>> import string |
| 36 | >>> collection = random.choices(string.ascii_letters + string.digits, k=100) |
| 37 | >>> binary_insertion_sort(collection) == sorted(collection) |
| 38 | True |
| 39 | """ |
| 40 | |
| 41 | n = len(collection) |
| 42 | for i in range(1, n): |
| 43 | value_to_insert = collection[i] |
| 44 | low = 0 |
| 45 | high = i - 1 |
| 46 | |
| 47 | while low <= high: |
| 48 | mid = (low + high) // 2 |
| 49 | if value_to_insert < collection[mid]: |
| 50 | high = mid - 1 |
| 51 | else: |
| 52 | low = mid + 1 |
| 53 | for j in range(i, low, -1): |
| 54 | collection[j] = collection[j - 1] |
| 55 | collection[low] = value_to_insert |
| 56 | return collection |
| 57 | |
| 58 | |
| 59 | if __name__ == "__main__": |
no outgoing calls
no test coverage detected