Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
oorrja
GitHub Repository: oorrja/learntosolveit
Path: blob/master/languages/cprogs/Ex_3.1_binsearch-2.c
1240 views
1
/* Binsearch function, by writing minimum tests inside the loop ( at the cost of more outside)*/
2
3
#include<stdio.h>
4
5
int binsearch(int x,int v[],int n);
6
7
int main(void)
8
{
9
int arr[]={2,4,6,7,9,29,45,46,49,50,51};
10
printf("%d",binsearch(9,arr,10));
11
12
return 0;
13
}
14
15
int binsearch(int x,int v[],int n)
16
{
17
int low,high,mid;
18
19
low=0;
20
high=n-1;
21
22
mid = ( low + high ) / 2;
23
24
while(low < high && x != v[mid])
25
{
26
if( x > v[mid])
27
low = mid+1;
28
else
29
high = mid -1;
30
31
mid = ( low + high)/2;
32
}
33
34
if(x==v[mid])
35
return mid;
36
else
37
return -1;
38
}
39
40
41