-
Notifications
You must be signed in to change notification settings - Fork 0
/
eg_sort_BinaryInsertionSort.cpp
58 lines (45 loc) · 1.15 KB
/
eg_sort_BinaryInsertionSort.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#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, j, selected, loc, k;
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;
cout << "Intermediate result : \n" << endl;
for(k = 0; k < n; k++)
cout << arr[k] << "\t";
cout << endl;
}
}
int main()
{
int arr[] = {12, 56, 1, 67, 45, 8, 82, 16, 63, 23};
int n = sizeof(arr)/sizeof(arr[0]);
int i;
BinaryInsertionSort(arr,n);
cout << "Sorted array is : \n" << endl;
for(i = 0; i < n; i++)
cout << arr[i] << "\t";
cout << endl;
return 0;
}