![]() |
VOOZH | about |
Given an array of integers, the task is to sort the elements in ascending order using Binary Insertion Sort. Unlike the traditional insertion sort, this algorithm uses binary search to find the correct position for inserting an element, which reduces unnecessary comparisons and makes sorting more efficient while maintaining a stable order.
For Example:
Input: [37, 23, 0, 17, 12, 72, 31, 46, 100, 88, 54]
Output: [0, 12, 17, 23, 31, 37, 46, 54, 72, 88, 100]
Explanation: The algorithm places each unsorted element into its correct position in the sorted portion of the array using binary search, resulting in a fully sorted list.
In this approach, we manually implement the binary search logic to find the correct position for inserting elements during sorting. This helps understand how binary insertion sort works internally.
Sorted array: [0, 12, 17, 23, 31, 37, 46, 54, 72, 88, 100]
Explanation:
In this method, the built-in bisect module is used to find the position where an element should be inserted to maintain the sorted order. The function bisect_left() returns the index where the element should go, reducing the need for manual binary search logic.
Sorted array: [0, 12, 17, 23, 31, 37, 46, 54, 72, 88, 100]
Explanation:
Please refer complete article on Binary Insertion Sort for more details!