-
Notifications
You must be signed in to change notification settings - Fork 460
/
BinSearch.c
40 lines (40 loc) · 898 Bytes
/
BinSearch.c
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
// Binary Search Program - Iterative
#include <stdio.h>
void readArr(int[],int);
int BinSearch(int[],int,int,int);
void main()
{
int A[20],n,key,i,x;
printf("Enter the number of elements: ");
scanf("%d",&n);
readArr(A,n);
printf("Enter the element to search: ");
scanf("%d",&key);
x=BinSearch(A,0,n-1,key);
if(x==-1)
printf("Element not found");
else
printf("Element found at position %d",x+1);
}
void readArr(int A[],int n)
{
int i;
printf("Enter %d number of elements: ",n);
for(i=0;i<n;i++)
scanf("%d",&A[i]);
}
int BinSearch(int A[],int lwr,int upr,int key)
{
int mid;
while(lwr<=upr)
{
mid=(lwr+upr)/2;
if(A[mid]==key)
return mid;
else if(A[mid]<key)
lwr=mid+1;
else
upr=mid-1;
}
return -1;
}