0

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

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

}

但是由于某种原因,当我运行它时,它只是继续运行并且不返回任何内容。

4

2 回答 2

3

这里的错误是:

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

你可能想要

lower = middle + 1;

upper = middle - 1;

反而。当找不到所需的数字时,您还需要显式返回某些内容。

于 2013-10-03T15:06:40.073 回答
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;
}
于 2013-10-03T15:42:32.760 回答