Open In App

Python Program for Binary Insertion Sort

Last Updated : 28 Aug, 2023
Comments
Improve
Suggest changes
2 Likes
Like
Report

We can use binary search to reduce the number of comparisons in normal insertion sort. Binary Insertion Sort find use binary search to find the proper location to insert the selected item at each iteration.  In normal insertion, sort it takes O(i) (at ith iteration) in worst case. we can reduce it to O(logi) by using binary search.

Python Program for Binary Insertion Sort


Output
Sorted array:
[0, 12, 17, 23, 31, 37, 46, 54, 72, 88, 100]

Time Complexity: O(n2) The algorithm as a whole still has a worst case running time of O(n2) because of the series of swaps required for each insertion.
Auxiliary Space: O(long)

Python Program for Binary Insertion Sort Implementation using bisect module

In this method, we are using bisect.bisect_left() function that returns the index at which the val should be inserted in the sorted array arr[start:end+1], so we just need to add the start index to get the correct index in the original array. The insertion_sort function is the same as in the original code.


Output
Sorted array:
[0, 12, 17, 23, 31, 37, 46, 54, 72, 88, 100]

Time Complexity: O(n^2)

Auxiliary Space: O(1)

Please refer complete article on Binary Insertion Sort for more details!


Next Article

Similar Reads