Binary Insertion Sort in C++


Binary Insertion sort is a special type up of Insertion sort which uses binary search algorithm to find out the correct position of the inserted element in the array.

Insertion sort is sorting technique that works by finding the correct position of the element in the array and then inserting it into its correct position.

Binary search is searching technique that works by finding the middle of the array for finding the element.

As the complexity of binary search is of logarithmic order, the searching algorithm’s time complexity will also decrease to of logarithmic order.

Implementation of binary Insertion sort. this program is a simple Insertion sort program but instead of the standard searching technique binary search is used.

Example

#include <iostream>
using namespace std;
int binarySearch(int arr[], int item, int low, int high) {
   if (high <= low)
      return (item > arr[low])? (low + 1): low;
      int mid = (low + high)/2;
   if(item == arr[mid])
      return mid+1;
   if(item > arr[mid])
      return binarySearch(arr, item, mid+1, high);
      return binarySearch(arr, item, low, mid-1);
}
void BinaryInsertionSort(int arr[], int n) {
   int i, loc, j, k, selected;
   for (i = 1; i < n; ++i) {
      j = i - 1;
      selected = arr[i];
      loc = binarySearch(arr, selected, 0, j);
      while (j >= loc) {
         arr[j+1] = arr[j];
         j--;
      }
      arr[j+1] = selected;
   }
}
int main() {
   int arr[] = {12, 56, 1, 67, 45, 8, 82, 16, 63, 23};
   int n = sizeof(arr)/sizeof(arr[0]), i;
   BinaryInsertionSort(arr, n);
      cout<<"Sorted array is : \n";
   for (i = 0; i < n; i++)
      cout<<arr[i]<<"\t";
   return 0;
}

Output

Sorted array is :
1 8 12 16 23 45 56 63 67 82

Updated on: 22-Nov-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements