简体   繁体   中英

(“vector subscript out of range”) for Binary search problem

I am trying to implement binary search function in C++, in this function I have sorted vector of integers, then I enter vector of integers to check the index of the value I am searching for, If value is not found -1 should be returned

The problem is I receive message _DEBUG_ERROR("vector subscript out of range"); while debugging.

Here is the code

 #include <iostream>
#include <cassert>
#include <vector>

using std::vector;

int binary_search(const vector<int> &a, int x, int left, int right) {
    left = 0;
    right = (int)a.size();
    if (left > right) return -1;
    int mid = (left + ((left - right) / 2));
    if (a[mid] == x)
    {
        return mid;
    }
    else if (x > mid)
    {
        return binary_search(a, x, mid + 1, right);
    }
    else if (x < mid)
        return binary_search(a, x, left, mid - 1);
}

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

int main() {
    int n;
    std::cin >> n;
    vector<int> a(n);
    for (size_t i = 0; i < a.size(); i++) {
        std::cin >> a[i];
    }
    int m;
    std::cin >> m;
    vector<int> b(m);
    int left =0;
    int right= (int)a.size() - 1 ;
    for (int i = 0; i < m; ++i) {
        std::cin >> b[i];
    }
    for (int i = 0; i < m-1; ++i) {

        std::cout << binary_search(a, b[i], left, right) << ' ';
    }
}

There are 2 problems with this code:

In the binary search function, you start with assigning your parameters with new values, which will lead to infinite recursion. Just remove this assignment.

Your mid is assigned like this int mid = (left + ((left - right) / 2)); but should be this: int mid = (left + ((right - left) / 2)); (your current mid is always less or equal to left, and your error comes up here, since you try to use negative index)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM