Problem Statement
Write a recursive c program to search an element using binary search
#include<stdio.h>
int binary_search(int sorted_list[], int low, int high, int element);
int main()
{
int element,b[20],i,y;
printf("enter the number to be searched ");
scanf("%d",&element);
printf("now enter the elments in assending order enter ctrl-d in the end \n");
i=0;
while(scanf("%d",&b[i])!=EOF)
{
i++;
}
y=binary_search(b,0,i-1,element);
if(y==-1)
{
printf("not found \n");
}
else
{
printf("found at the position %d",y);
}
return 0;
}
int binary_search(int sorted_list[], int low, int high, int element) {
if (high < low)
return -1;
int middle = low + (high - low)/2;
if (element < sorted_list[middle])
return binary_search(sorted_list, low, middle-1, element);
else if (element > sorted_list[middle])
return binary_search(sorted_list, middle+1, high, element);
else
return middle;
}
Write a recursive c program to search an element using binary search
#include<stdio.h>
int binary_search(int sorted_list[], int low, int high, int element);
int main()
{
int element,b[20],i,y;
printf("enter the number to be searched ");
scanf("%d",&element);
printf("now enter the elments in assending order enter ctrl-d in the end \n");
i=0;
while(scanf("%d",&b[i])!=EOF)
{
i++;
}
y=binary_search(b,0,i-1,element);
if(y==-1)
{
printf("not found \n");
}
else
{
printf("found at the position %d",y);
}
return 0;
}
int binary_search(int sorted_list[], int low, int high, int element) {
if (high < low)
return -1;
int middle = low + (high - low)/2;
if (element < sorted_list[middle])
return binary_search(sorted_list, low, middle-1, element);
else if (element > sorted_list[middle])
return binary_search(sorted_list, middle+1, high, element);
else
return middle;
}
No comments:
Post a Comment