|
| 1 | + |
| 2 | +// C program for implementation of binary insertion sort |
| 3 | +#include <stdio.h> |
| 4 | + |
| 5 | +// A binary search based function to find the position |
| 6 | +// where item should be inserted in a[low..high] |
| 7 | +int binarySearch(int a[], int item, int low, int high) |
| 8 | +{ |
| 9 | + if (high <= low) |
| 10 | + return (item > a[low])? (low + 1): low; |
| 11 | + |
| 12 | + int mid = (low + high)/2; |
| 13 | + |
| 14 | + if(item == a[mid]) |
| 15 | + return mid+1; |
| 16 | + |
| 17 | + if(item > a[mid]) |
| 18 | + return binarySearch(a, item, mid+1, high); |
| 19 | + return binarySearch(a, item, low, mid-1); |
| 20 | +} |
| 21 | + |
| 22 | +// Function to sort an array a[] of size 'n' |
| 23 | +void insertionSort(int a[], int n) |
| 24 | +{ |
| 25 | + int i, loc, j, k, selected; |
| 26 | + |
| 27 | + for (i = 1; i < n; ++i) |
| 28 | + { |
| 29 | + j = i - 1; |
| 30 | + selected = a[i]; |
| 31 | + |
| 32 | + // find location where selected sould be inseretd |
| 33 | + loc = binarySearch(a, selected, 0, j); |
| 34 | + |
| 35 | + // Move all elements after location to create space |
| 36 | + while (j >= loc) |
| 37 | + { |
| 38 | + a[j+1] = a[j]; |
| 39 | + j--; |
| 40 | + } |
| 41 | + a[j+1] = selected; |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +// Driver program to test above function |
| 46 | +int main() |
| 47 | +{ |
| 48 | + int a[] = {37, 23, 0, 17, 12, 72, 31, |
| 49 | + 46, 100, 88, 54}; |
| 50 | + int n = sizeof(a)/sizeof(a[0]), i; |
| 51 | + |
| 52 | + insertionSort(a, n); |
| 53 | + |
| 54 | + printf("Sorted array: \n"); |
| 55 | + for (i = 0; i < n; i++) |
| 56 | + printf("%d ",a[i]); |
| 57 | + |
| 58 | + return 0; |
| 59 | +} |
0 commit comments