Easy Programming All

Easy Programming All

Monday, December 17, 2018

WAP in C to Search an element in an array using Binary Search

#include<stdio.h>
int main()
{
int i,a[100],n,search,first,last,middle;
printf("How many array elements you want to Enter\n");
scanf("%d",&n);
printf("Enter an array elements\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
printf("which elements you want to search\n");
scanf("%d",&search);
first=0;
last=n-1;
middle=(first+last)/2;
while(first<=last)
{
if(a[middle]<search)
{
first=middle+1;
}
else if(a[middle]==search)
{
printf("%d element is at %d location",search,middle+1);
break;
}
else
{
first=middle-1;
}
middle=(first+last)/2;
}
if(first>last)
{
printf("%d element is not present in this array",search);
}
return 0;
}

INPUT 1:
How many array elements you want to Enter
5
Enter an array elements
11
22
33
44
55
which elements you want to search
33
OUTPUT 1:
 33 element is at 3 location


INPUT 2:
How many array elements you want to Enter
5
Enter an array elements
11
22
33
44
55
which elements you want to search
66
OUTPUT 1:
 66 element is not present in this array







No comments:

Post a Comment