-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathbinarySearch.c
More file actions
31 lines (31 loc) · 761 Bytes
/
binarySearch.c
File metadata and controls
31 lines (31 loc) · 761 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
#include <stdio.h>
int main()
{
int i, low, high, mid, n, key, array[100];
printf("Enter number of elementsn");
scanf("%d", &n);
printf("Enter %d integersn", n);
for (i = 0; i < n; i++)
scanf("%d", &array[i]);
printf("Enter value to findn");
scanf("%d", &key);
low = 0;
high = n - 1;
mid = (low + high) / 2;
while (low <= high)
{
if (array[mid] < key)
low = mid + 1;
else if (array[mid] == key)
{
printf("%d found at location %d.n", key, mid + 1);
break;
}
else
high = mid - 1;
mid = (low + high) / 2;
}
if (low > high)
printf("Not found! %d isn't present in the list.n", key);
return 0;
}