Skip to content
Related Articles

Related Articles

Java Program for Binary Insertion Sort

View Discussion
Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 13 Jun, 2022
View Discussion
Improve Article
Save Article

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.

Java

 

Java




// Java Program implementing
// binary insertion sort
 
import java.util.Arrays;
class GFG
{
    public static void main(String[] args)
    {
        final int[] arr = {37, 23, 0, 17, 12, 72, 31,
                             46, 100, 88, 54 };
 
        new GFG().sort(arr);
 
        for(int i=0; i<arr.length; i++)
            System.out.print(arr[i]+" ");
    }
 
    public void sort(int array[])
    {
        for (int i = 1; i < array.length; i++)
        {
            int x = array[i];
 
            // Find location to insert using binary search
            int j = Math.abs(Arrays.binarySearch(array, 0, i, x) + 1);
 
            //Shifting array to one location right
            System.arraycopy(array, j, array, j+1, i-j);
 
            //Placing element at its correct location
            array[j] = x;
        }
    }
}
 
// Code contributed by Mohit Gupta_OMG

Time Complexity: O(n2)  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. 
Auxiliary Space: O(1)

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


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!