Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected Output of linear search

Please find my code below for linear search. Binary search function is giving the correct output. But after doing the stress testing I am not getting the correct output of linear search. When implementing the same code for linear search with the same input(test case) as produced by stress testing the code gives correct output.

int linear_search(const vector<int> &a, int x) 
{
  for (int i = 0; i < a.size(); ++i) 
  {
    if (a[i] == x)
    {
      return i;
    }
  }
  return -1;
}

main function

int main() {
   while(true)
   {
     int n=5;
   vector<int> a(n);
   for (size_t i = 0; i < n; i++) {
     int b = rand() % 5 + 1;
     a.push_back(b);
   }
   for (size_t i = 0; i < n; i++) {
     std::cout<<a[i]<<" ";
   }
   std::cout<<"\n";
   int x = rand() % 10 + 1;
   std::cout<<x<<"\n";
   int l = linear_search(a,x);
   int b = binary_search(a,x);
   if(l != b)
   {

     std::cout<<l<<"\n";
     std::cout<<b<<"\n";
     break;
   }
   else
   {
     std::cout<<"Ok\n";
   }
   }
}

After running the above code, I am getting wrong(unexpected) output when the random input(produced by stress testing) is :

0 0 0 0 0

4

The output of linear search is 5 instead of -1. I am unable to find the error.

like image 784
Jarv Potter Avatar asked Dec 18 '25 19:12

Jarv Potter


1 Answers

You are creating a vector with n elements here:

vector<int> a(n);

and then additionally push_backing n elements.

This results in n*2 elements in a, and in linear_search, you are looking at all of them. My guess is that the 5th index has the value 4 in this particular test case.

like image 183
cigien Avatar answered Dec 20 '25 11:12

cigien



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!