1

So basically,I am doing a code which searches for an element of a vector inside a vector.While I thought of the approach , implementing it got me a segmentation error. I narrowed down the problem

In the code if I decomment the line in the for loop while commenting the above then all elements of B[i] are being displayed.Why then is a segmentation error being thrown. I think the binary_return is more or less correct and if I replace the line with binary_return(A,0,A.size(),B[1]) then its working. Here is the code:

#include<iostream>
#include<vector>

using namespace std;

int binary_return(vector<int> a,int start,int end,int seek)
{
    int mid = (start+end)/2;
    //cout<<start<<" "<<seek<<" "<<mid;
    if(end!=start)
    {
        if(a[mid]==seek)
        {
            return mid;
        }
        else if(a[mid]>seek)
        {
            return binary_return(a,start,mid,seek);
        }
        else if(a[mid]<seek)
        {
            return binary_return(a,mid,end,seek);
        }
    }
    else
        return -1;
}

int main()
{
    vector<int> A{1,3,6,9,23};
    vector<int> B{1,4,23};
    cout<<B[0]<<B[1]<<B[2];
    for(int i=0;i<B.size();i++)
    {
        cout<<binary_return(A,0,A.size(),B[i]);
        //cout<<binary_return(A,0,A.size(),B[0]);
    }
    return 1;
}
6502
  • 112,025
  • 15
  • 165
  • 265
user34096
  • 15
  • 5

2 Answers2

1

Your code is not handling the last case correctly and ends up in infinite recursion.

This unfortunately in C++ means that anything can happen (you're not guaranteed to get a meaningful error).

Add a debug print at the beginning of the function and you'll see in which cases you're entering infinite recursion.

6502
  • 112,025
  • 15
  • 165
  • 265
-1

You have infinite recursion in third if statment The correct code if the following:

#include<iostream>
#include<vector>

using namespace std;

int binary_return(vector<int> a,int start,int end,int seek)
{
    int mid = (start+end)/2;
    //cout<<start<<" "<<seek<<" "<<mid;
    if(end!=start)
    {
        if(a[mid]==seek)
        {
            return mid;
        }
        else if(a[mid]>seek)
        {
            return binary_return(a,start,mid,seek);
        }
        else if(a[mid]<seek)
        {
            // In your sample you forgot to add +1 (mid+1) for next start
            return binary_return(a,mid+1,end,seek);
        }
    }
    else
        return -1;
}

int main()
{
    vector<int> A{1,3,6,9,23};
    vector<int> B{1,4,23};
    for(int i=0;i<B.size();i++)
    {
        cout<<binary_return(A,0,A.size(),B[i]);
    }
    return 0;
}
Denis Kotov
  • 857
  • 2
  • 10
  • 29