-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary search.cpp
More file actions
38 lines (38 loc) · 852 Bytes
/
binary search.cpp
File metadata and controls
38 lines (38 loc) · 852 Bytes
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
#include <stdio.h>
int main()
{
int n, i, a, low, high, mid;
printf("Enter the number of elements: \n");
scanf("%d", &n);
int array[n];
printf("Enter the elements in sorted order: \n");
for (i = 0; i < n; i++)
{
scanf("%d", &array[i]);
}
printf("Enter the value to search: \n");
scanf("%d", &a);
low = 0;
high = n - 1;
mid = (low + high) / 2;
while (low <= high)
{
if (array[mid] < a)
low = mid + 1;
else if (array[mid] == a)
{
printf("%d found at %d", a, mid);
break;
}
else
{
high = mid - 1;
mid = (low + high) / 2;
}
}
if (low > high)
{
printf("%d is not present in the array ", a);
return 0;
}
}