VOOZH about

URL: https://www.geeksforgeeks.org/dsa/binary-insertion-sort/

⇱ Binary Insertion Sort - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Binary Insertion Sort

Last Updated : 23 Jul, 2025

Binary insertion sort is a sorting algorithm which is similar to the insertion sort, but instead of using linear search to find the location where an element should be inserted, we use binary search. Thus, we reduce the comparative value of inserting a single element from O (N) to O (log N).

It is a flexible algorithm, which means it works faster when the same given members are already heavily sorted, i.e., the current location of the feature is closer to its actual location in the sorted list.

It is a stable filtering algorithm - elements with the same values ??appear in the same sequence in the last order as they were in the first list.

Applications of Binary Insertion sort:

  • Binary insertion sort works best when the array has a lower number of items.
  • When doing quick sort or merge sort, when the subarray size becomes smaller (say <= 25 elements), it is best to use a binary insertion sort.
  • This algorithm also works when the cost of comparisons between keys is high enough. For example, if we want to filter multiple strings, the comparison performance of two strings will be higher.

How Does Binary insertion sort Work?

  • In the binary insertion sort mode, we divide the same members into two subarrays - filtered and unfiltered. The first element of the same members is in the organized subarray, and all other elements are unplanned.
  • Then we iterate from the second element to the last. In the repetition of the i-th, we make the current object our "key". This key is a feature that we should add to our existing list below.
  • In order to do this, we first use a binary search on the sorted subarray below to find the location of an element larger than our key. Let's call this position “pos.” We then right shift all the elements from pos to 1 and created Array[pos] = key.
  • We can note that in every i-th multiplication, the left part of the array till (i - 1) is already sorted.

Approach to implement Binary Insertion sort:

  • Iterate the array from the second element to the last element.
  • Store the current element A[i] in a variable key.
  • Find the position of the element just greater than A[i] in the subarray from A[0] to A[i-1] using binary search. Say this element is at index pos.
  • Shift all the elements from index pos to i-1 towards the right.
  • A[pos] = key.

Below is the implementation for the above approach:


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

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

Another approach: Following is an iterative implementation of the above recursive code


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


 

Comment