< Back to forum

implementation of binary search

my code for binary search is not working....where i am wrong....here my code goes :

#include<bits/stdc++.h>
using namespace std;
int BS(int[],int,int,int);
int main()
{
 int n;
 scanf("%d",&n);
 int a[n],i;
 for(i=0;i<n;i++)
 {
  scanf("%d",&a[i]);
 }
 sort(a,a+n);
 int t;
 scanf("%d",&t);
 while(t--)
  {
  int numberToSearch;
  scanf("%d",&numberToSearch);
   int r;
   r = BS(a,0,n-1,numberToSearch);
   printf("%d\n",r);
     }
return 0; 
}
int BS(int x[],int f,int l,int test)
{
 int mid;
 while(f<=l)
 { 
 mid=(l-f)/2+f;
 if(x[mid]==test)
 {
  return (mid);
 }
 else if(x[mid]<test)
 {
  l=mid+1;
 }
 else
 {
  f=mid-1;
 }
    }
 return (-1);
}

Asked by: Abhishek_Chaudhary on April 7, 2019, 6:34 p.m. Last updated on April 7, 2019, 6:34 p.m.


Enter your answer details below:


Preview

Enter your comment details below:

Preview




1 Answer(s)

avatar

You should better check the values you are assigning to the lowerbound and upperbound of your binary search.

Gyanesha_Prajjwal last updated on April 7, 2019, 6:34 p.m. 0    Reply    Upvote   

Instruction to write good question
  1. 1. Write a title that summarizes the specific problem
  2. 2. Pretend you're talking to a busy colleague
  3. 3. Spelling, grammar and punctuation are important!

Bad: C# Math Confusion
Good: Why does using float instead of int give me different results when all of my inputs are integers?
Bad: [php] session doubt
Good: How can I redirect users to different pages based on session data in PHP?
Bad: android if else problems
Good: Why does str == "value" evaluate to false when str is set to "value"?

Refer to Stack Overflow guide on asking a good question.