Ad
Recursive Binary Search Program C
The following code works good if the key is less than equal to 11 but if the key is greater than 11 it does not return anything.
#include<stdio.h>
#include<time.h>
int BinaryS(int a[],int l, int h,int key)
{
if(h >= l){
int mid = (h-l)/2;
if(a[mid] == key)
return mid;
if(a[mid] > key)
return BinaryS(a,l,mid-1,key);
return BinaryS(a,mid+1,h,key);
}
return -1;
}
int main(void)
{
int a[]={10,11,15,19,22,23,30,40,45,50};
int n;
printf("Enter the number to be searched\n");
scanf("%d",&n);
int num=10;
int clock_t,start_t,end_t,total;
start_t = clock();
int f = BinaryS(a,0,num-1,n);
end_t = clock();
total = (end_t-start_t)/CLOCKS_PER_SEC;
printf("Time taken: %d\n",total);
if(f == -1){
printf("Key not found in the array ");
}
else{
printf("Key found at: %d",f+1);
}
return 0;
}
Ad
Answer
int mid = (h-l)/2;
is wrong for sure. mid
should be (h + l)/2
.
Ad
source: stackoverflow.com
Related Questions
- → OctoberCMS Backend Loging Hash Error
- → "failed to open stream" error when executing "migrate:make"
- → OctoberCMS - How to make collapsible list default to active only on non-mobile
- → Create plugin that makes objects from model in back-end
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → How to install console for plugin development in October CMS
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → How to update data attribute on Ajax complete
- → October CMS - Conditionally Load a Different Page
Ad