Write a function that takes an integer array and an integer variable as an argument. The function then finds the position of the element in the array using binary search algorithm. Assume that the array is sorted in ascending order.
Answers
Answered by
1
#include<stdio.h>
void main()
{
int a[10],e,low,high,mid,flag=0,i;
clrscr();
printf("enter any 10 elements in an ascending order\n");
for(i=0;i<10;i++)
scanf("%d",&a[i]);
binarysearch(a,10);
getch();
}
void binarysearch(int a[], int n)
{
int e;
printf("enter the element to be searched\n");
scanf("%d",&e);
low=0;
high=9;
while(low<=high)
{
mid=(low+high)/2;
if(e==a[mid])
{
flag=1;
break;
}
elseif(e>a[mid])
low=mid+1;
else if(e<a[mid])
high=mid-1;
}
if(flag==0)
printf("element not found\n");
else
printf("element found at %d position", mid+1);
}
void main()
{
int a[10],e,low,high,mid,flag=0,i;
clrscr();
printf("enter any 10 elements in an ascending order\n");
for(i=0;i<10;i++)
scanf("%d",&a[i]);
binarysearch(a,10);
getch();
}
void binarysearch(int a[], int n)
{
int e;
printf("enter the element to be searched\n");
scanf("%d",&e);
low=0;
high=9;
while(low<=high)
{
mid=(low+high)/2;
if(e==a[mid])
{
flag=1;
break;
}
elseif(e>a[mid])
low=mid+1;
else if(e<a[mid])
high=mid-1;
}
if(flag==0)
printf("element not found\n");
else
printf("element found at %d position", mid+1);
}
Similar questions
Science,
7 months ago
Social Sciences,
7 months ago
Math,
1 year ago
Physics,
1 year ago
English,
1 year ago