C ++二进制搜索算法不起作用

时间:2013-10-03 15:04:03

标签: c++ binary-search

所以我有一个名为bList的int的向量,其中已有信息。我在运行二进制搜索之前对它进行了排序。

//I have already inserted random ints into the vector


//Sort it
bubbleSort();
//Empty Line for formatting
cout << "\n";
//Print out sorted array.
print();

cout << "It will now search for a value using binary search\n";

int val = binSearch(54354);
cout<<val;

我的冒泡排序算法确实有效。

我让它返回一个int,它是列表中搜索值的位置。

//Its one argument is the value you are searching for.
int binSearch(int isbn) {
    int lower = 0;
    int upper = 19;//Vector size is 20.
    int middle = (lower + upper) / 2;

    while (lower < upper) {
        middle = (lower + upper) / 2;
        int midVal = bList[middle];

        if (midVal == isbn) {
            return middle;
            break;
        } else if (isbn > midVal) {
            lower = midVal + 1;
        } else if (isbn < midVal) {
            upper - midVal - 1;
        }
    }

}

但出于某种原因,当我运行它时,它只是继续运行而不返回任何东西。

2 个答案:

答案 0 :(得分:3)

这里的错误是:

// ... 
} else if (isbn > midVal) {
    lower = midVal + 1;
} else if (isbn < midVal) {
    upper - midVal - 1;
}

你可能想要

lower = middle + 1;

upper = middle - 1;

代替。 当无法找到所需的数字时,您还需要显式返回。

答案 1 :(得分:1)

你的while条件仍有轻微的逻辑问题:

int binary_search(int i, const std::vector<int>& vec) // you really should pass in the vector, if not convert it to use iterators
{
    int result = -1; // default return value if not found
    int lower = 0;
    int upper = vec.size() - 1;

    while (lower <= upper)  // this will let the search run when lower == upper (meaning the result is one of the ends)
    {
        int middle = (lower + upper) / 2;
        int val = vec[middle]; 

        if (val == i)
        {
            result = middle;
            break;
        }
        else if (i > val)
        {
            lower = middle + 1; // you were setting it to the value instead of the index
        }
        else if (i < val)
        {
            upper = middle - 1; // same here
        }
    }

    return result;  // moved your return down here to always return something (avoids a compiler error)
}

或者,您可以将其切换为使用迭代器:

template<class RandomIterator>
RandomIterator binary_search(int i, RandomIterator start, RandomIterator end)
{
    RandomIterator result = end;

    while (start <= end) // this will let the search run when start == end (meaning the result is one of the ends)
    {
        RandomIterator middle = start + ((end - start) / 2);

        if (*middle == i)
        {
            result = middle;
            break;
        }
        else if (i > *middle)
        {
            start = middle + 1;
        }
        else if (i < *middle)
        {
            end = middle - 1;
        }
    }

    return result;
}