-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathbinarySearch.c
More file actions
60 lines (46 loc) · 806 Bytes
/
binarySearch.c
File metadata and controls
60 lines (46 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
53
54
55
56
57
58
59
60
/*
Binary Search
Assuming array is already sorted.
*/
//created by akashbhalotia
#include <stdio.h>
void input(int a[], int N) //takes array input
{
int i;
for(i=0;i<N;i++)
{
printf("Enter a number\n");
scanf("%d",&a[i]);
}
}
int binSearch(int a[], int N, int key) //binary search
{
int l=0,r=N-1,mid;
while(l<=r)
{
mid=(l+r)/2;
if(a[mid]==key)
return mid;
else if(a[mid]<key)
l=mid+1;
else
r=mid-1;
}
return -1;
}
int main()
{
int i,N,key,pos;
printf("Enter number of elements\n");
scanf("%d",&N);
int a[N];
input(a,N);
printf("Enter a number to be searched\n");
scanf("%d",&key);
pos=binSearch(a,N,key);
if(pos==-1)
printf("Element not present in array\n");
else
printf("Element found at index: %d, (0-indexed)\n",pos);
return 0;
}