Skip to content

Commit ffac6ec

Browse files
Merge pull request #737 from kokum007/master
add new binary search in c
2 parents 2eae153 + cb93282 commit ffac6ec

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
#include <stdio.h>
2+
3+
int main()
4+
{
5+
int s, first, last, middle, n, search, array[100];
6+
7+
printf("Enter number of elements\n");
8+
scanf("%d",&n);
9+
10+
printf("Enter %d integers\n", n);
11+
12+
for (s = 0; s < n; s++)
13+
scanf("%d",&array[s]);
14+
15+
printf("Enter value to find\n");
16+
scanf("%d", &search);
17+
18+
first = 0;
19+
last = n - 1;
20+
middle = (first+last)/2;
21+
22+
while (first <= last) {
23+
if (array[middle] < search)
24+
first = middle + 1;
25+
else if (array[middle] == search) {
26+
printf("%d found at location %d.\n", search, middle+1);
27+
break;
28+
}
29+
else
30+
last = middle - 1;
31+
32+
middle = (first + last)/2;
33+
}
34+
if (first > last)
35+
printf("Not found! %d isn't present in the list.\n", search);
36+
37+
return 0;
38+
}

0 commit comments

Comments
 (0)