[英]This simple c++ program runs forever and I can't figure out why
It compiles fine, prints the first "start" but it stops right there. 它编译良好,打印出第一个“开始”,但在此处停止。 Any help is greatly appreciated. 任何帮助是极大的赞赏。 I spent several hours trying to figure out whats wrong and tried running it within several different IDEs. 我花了几个小时试图找出问题所在,并尝试在多个不同的IDE中运行它。 I think it fails at the while-loop. 我认为它在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;
}
Your ternary_search
function doesn't have a means to return when it fails to find the value in the search table. 当您的ternary_search
函数无法在搜索表中找到值时,它没有返回方法。 It returns only when it finds an element in the table that exactly matches the value you pass in. 仅当在表中找到与您传递的值完全匹配的元素时,它才返回。
Since the second invocation of the function is called with i+1
-- which is 1 -- which is not a member of your table, your ternary search function never exits. 由于该函数的第二次调用是使用i+1
(即1)调用的,它不是表的成员,因此三元搜索函数永远不会退出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.