-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_insertion-Sort.h
More file actions
44 lines (37 loc) · 1.05 KB
/
binary_insertion-Sort.h
File metadata and controls
44 lines (37 loc) · 1.05 KB
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
// binary insertion sort
// A binary search based function
// to find the position
// where item should be inserted
// in a[low..high]
int binarySearch(long long int a[], long long int item, long long int low, long long 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);
}
// Function to sort an array a[] of size 'n'
void insertionSort2(long long int a[], long long int n)
{
int i, loc, j, k, selected;
for (i = 1; i < n; ++i)
{
j = i - 1;
selected = a[i];
// find location where selected sould be inseretd
loc = binarySearch(a, selected, 0, j);
// Move all elements after location to create space
while (j >= loc)
{
a[j + 1] = a[j];
j--;
}
a[j + 1] = selected;
}
}