基于数组的实现的递归搜索

时间:2013-08-25 02:04:21

标签: c++ recursion

我在这个程序上遇到了一些麻烦,我无法弄清楚我做错了什么;该程序应该是一个递归搜索程序,但有些功能没有被正确调用(或根本没有)。该问题似乎以“bin_search”部分为中心,并且“int data [size]”部分再次出现错误,说“可能无法初始化可变大小的对象”。任何帮助将不胜感激。提前谢谢!

# include <iostream> // Allows program to perform input and output
using std::cout; // program uses cout
using std::cin; // program uses cin



int bin_search ( int data[], int left, int right, int key, int NOT_FOUND)
{
 // calculate the index to search
 int index = ( ( ( key - data[ left ]) / ( data[ right ] - data[ left] ) )* (right - left)         ) + left;
 // terminating condition
 if ( data[index] == key )
 return key;
 // terminating condition
 if ( left >= right )
 return NOT_FOUND;
 // search recursively
 if ( key < data[index] )
 return bin_search ( data, left, index-1, key );
 else
 return bin_search ( data, index + 1, right, key );
}
    // end function bin search

int main()
{
 // function main begins program execution
  int size = 10;
  int bin;
  int data[size] = {0, 7, 12, 23, 44, 335, 426, 477, 658, 921};
  int key = 23;
 // let the user know about the program
 cout << "\n\n A program to search an element recursively.";
 // search and print the results to the user
 if ( bin_search( data, 0, size-1, key ) == key )
 cout << "\n\n\tThe key was found.";
 else
 cout << "\n\n\tThe key was not found.";
 // let the screen wait to see the output
 cout << "\n\n\t";
 system( "pause" );
 return 0; // indicate program executed successfully
 // end of function, main
}

1 个答案:

答案 0 :(得分:2)

一些注意事项:

  1. 当有n个元素时,您希望拥有n + 1个职位!通过这种方式,您可以轻松处理空序列,如果找不到某些内容,则会返回明显的结果。
  2. 找到要检查的index的计算远非复杂。您只需要找到要搜索的序列的中间位置。 key肯定不是此计算的一部分。
  3. 您需要处理序列为空的情况。
  4. 就个人而言,我不会递归地实现二进制搜索,特别是如果调用不是尾递归的。
  5. 在讨论个人偏好时,无论如何我都会用迭代器来实现它。