Search code examples
c++vectorbinary-search-treebinary-search

Vector error,a very confusing segmentation error?


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;
}

Solution

  • 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;
    }