-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBinary Search Algorithm.c
More file actions
69 lines (57 loc) · 1.05 KB
/
Binary Search Algorithm.c
File metadata and controls
69 lines (57 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/**
* @author: Ashish A Gaikwad <ash.gkwd@gmail.com>
* Binary Search Algorithm in C with menu driven program
*/
#include <stdio.h>
#define MAX 30
int series[MAX];
int main()
{
int start, mid, end;
int total, input, temp;
printf("Enter number of values : ");
scanf("%d", &total);
for (int i = 0; i < total; ++i)
{
printf("Enter value %d : ", i+1);
scanf("%d", &series[i]);
}
// Sort the input using Insertion sort
for (int i = 0; i < total; ++i)
{
for (int j = i-1; j >= 0; --j)
{
if(series[j] > series[j+1])
{
temp = series[j];
series[j] = series[j+1];
series[j+1] = temp;
}
else break;
}
}
printf("Enter value to search : ");
scanf("%d", &input);
// Let the Binary Search begin
start = 0;
end = total - 1;
while(start <= end)
{
mid = (start + end)/2;
if(input == series[mid])
{
printf("Value %d is found at index %d\n", input, mid);
return 0;
}
else if(input < series[mid])
{
end = mid - 1;
}
else
{
start = mid + 1;
}
}
printf("Value %d not found\n", input);
return 0;
}