From 2adb6710068bcfb943cc1465579c9ed4a301f5cf Mon Sep 17 00:00:00 2001 From: Siddharth Choudhary <32647636+siddharthzs654@users.noreply.github.com> Date: Fri, 11 Oct 2019 06:18:58 +0530 Subject: [PATCH] Added Binary-insertionsort.cpp Time Complexity O(nlogn) But, Only corn is Number of comparison is still O(n^2) --- Algorithms/Sorting/binary-insertionsort.cpp | 52 +++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 Algorithms/Sorting/binary-insertionsort.cpp diff --git a/Algorithms/Sorting/binary-insertionsort.cpp b/Algorithms/Sorting/binary-insertionsort.cpp new file mode 100644 index 0000000..b6be272 --- /dev/null +++ b/Algorithms/Sorting/binary-insertionsort.cpp @@ -0,0 +1,52 @@ +#include + +using namespace std; + + +int binarySearch(int a[], int item, int low, int high) +{ + if (high <= low) + return (item > a[low])? (low + 1): low; + + int mid = (low + high)/2; + + if(item == a[mid]) + return mid+1; + + if(item > a[mid]) + return binarySearch(a, item, mid+1, high); + return binarySearch(a, item, low, mid-1); +} + +void insertionSort(int a[], int n) +{ + int i, loc, j, k, selected; + + for (i = 1; i < n; ++i) + { + j = i - 1; + selected = a[i]; + + loc = binarySearch(a, selected, 0, j); + + while (j >= loc) + { + a[j+1] = a[j]; + j--; + } + a[j+1] = selected; + } +} + +int main() +{ + + int arr[10] = {2,4,10,1,1,7,4,5,1,8}; + insertionSort(arr, 10); + + printf("Sorted array: \n"); + for (int i = 0; i < 10; i++) + printf("%d ",arr[i]); + + return 0; +}