Skip to content

Commit 598f0d5

Browse files
authored
Merge pull request pratyushmp#148 from Kartik-Ganiga/master
Binary search in C
2 parents 51b2fc3 + 9f47272 commit 598f0d5

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

c/binarySearch.c

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
#include <stdio.h>
2+
int main()
3+
{
4+
int i, low, high, mid, n, key, array[100];
5+
printf("Enter number of elementsn");
6+
scanf("%d",&n);
7+
printf("Enter %d integersn", n);
8+
for(i = 0; i < n; i++)
9+
scanf("%d",&array[i]);
10+
printf("Enter value to findn");
11+
scanf("%d", &key);
12+
low = 0;
13+
high = n - 1;
14+
mid = (low+high)/2;
15+
while (low <= high) {
16+
if(array[mid] < key)
17+
low = mid + 1;
18+
else if (array[mid] == key) {
19+
printf("%d found at location %d.n", key, mid+1);
20+
break;
21+
}
22+
else
23+
high = mid - 1;
24+
mid = (low + high)/2;
25+
}
26+
if(low > high)
27+
printf("Not found! %d isn't present in the list.n", key);
28+
return 0;
29+
}

0 commit comments

Comments
 (0)