[英]This simple c++ program runs forever and I can't figure out why
它編譯良好,打印出第一個“開始”,但在此處停止。 任何幫助是極大的贊賞。 我花了幾個小時試圖找出問題所在,並嘗試在多個不同的IDE中運行它。 我認為它在while循環中失敗。
#ifndef TERNARY_SEARCH_H
#define TERNARY_SEARCH_H
#include <cstdlib>
#include <iostream>
template <typename ArrayLike, typename T>
int ternary_search(const ArrayLike& array, const T& value, int low, int high)
{
/*
* low is the lowest possible index, high is the highest possible index
* value is the target value we are searrching for
* array is the ascending order array we are searching
*/
bool found = false;
while(!found)
{
int lowerThirdIndex = (((high - low)/(3)) + low);
int upperThirdIndex = (2*((high - low)/(3)) + low);
// search lower third
if (array[lowerThirdIndex] == value)
{
return lowerThirdIndex;
found = true;
}
else if (array[lowerThirdIndex] > value)
{
high = lowerThirdIndex;
}
else // array[lowerThirdIndex] < value
{
low = lowerThirdIndex;
}
//search upper third
if (array[upperThirdIndex] == value)
{
return upperThirdIndex;
found = true;
}
else if (array[upperThirdIndex] > value)
{
high = upperThirdIndex;
}
else // array[upperThirdIndex] < value
{
low = upperThirdIndex;
}
}
return -1;
}
#endif /* TERNARY_SEARCH_H */
//main.cpp
#include "ternary_search.h"
using namespace std;
int main() {
cout << "start";
int nums[] = {0, 10, 20, 30, 40, 50, 60, 70, 80, 90};
for (int i = 0; i <= 90; i += 10) {
if (ternary_search(nums, i, 0, 10) != i / 10) {
std::cout
<< "Searching for " << i << " returned index "
<< ternary_search(nums, i, 0, 10) << " instead of "
<< i / 10 << "." << std::endl;
return 1;
}
// search for something that doesn't exist.
if (ternary_search(nums, i + 1, 0, 10) != -1) {
std::cout
<< "Searching for " << i + 1 << " returned index "
<< ternary_search(nums, i + 1, 0, 10) << " instead of -1."
<< std::endl;
return 1;
}
}
std::cout << "On this small example, your search algorithm seems correct.\n";
return 0;
}
當您的ternary_search
函數無法在搜索表中找到值時,它沒有返回方法。 僅當在表中找到與您傳遞的值完全匹配的元素時,它才返回。
由於該函數的第二次調用是使用i+1
(即1)調用的,它不是表的成員,因此三元搜索函數永遠不會退出。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.