#include<stdio.h>
int main()
{
int a[100],i,n,s,k;
clrscr();
printf("\nEnter the length of array:");
scanf("%d",&n);
printf("\n Enter distinct elements of array: ");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("\nEnter the searching element: ");
scanf("%d",&s);
k=binary(a,s,n);
if(k!=-1)
printf("\n\nThe searching element is at %d",k+1);
else
printf("\n\nThe element is not found in the array");
return 0;
}
int binary(int a[],int p,int q)
{
int hi,low=0,mid;
hi=q-1;
while(low<=hi)
{
mid=(low+hi)/2;
if(p==a[mid])
return(mid);
if(p<a[mid])
hi=mid-1;
else
low=mid+1;
}
return(-1);
}
Output:
Enter the length of array: 20
Enter distinct element of array: 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Enter the searching element: 20
The searching element is at 20
No comments:
Post a Comment