-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinarySearch.c
More file actions
54 lines (50 loc) · 806 Bytes
/
Copy pathbinarySearch.c
File metadata and controls
54 lines (50 loc) · 806 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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <stdio.h>
/*
The array given should be sorted.
returns the index of the element in the array.
returns -1 if element is not found.
*/
int bSearch(int array[],int length,int key)
{
int high=length-1,low=0;
int mid=(high+low)/2;;
while(low<=high)
{
// element found.
if(array[mid]==key)
{
return mid;
}
else if(array[mid]>key)
{
high=mid-1;
}
else
{
low=mid+1;
}
mid=(high+low)/2;
}
// element not found in the array.
return -1;
}
int main()// driver
{
int i,j,k,l,m,n,t;
scanf("%d", &t);
while(t--)
{
scanf("%d",&n);
int a[n];
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
// value to be searched.
int key;
scanf("%d",&key);
int result =bSearch(a,n,key);
printf("%d\n",result);
}
return 0;
}