1

このプログラムに問題があり、何が間違っているのかわかりません。プログラムは再帰的な検索プログラムであると想定されていますが、一部の関数が正しく呼び出されていません (またはまったく呼び出されていません)。問題は "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
}
4

1 に答える 1

2

いくつかのメモ:

  1. n要素がある場合は、n + 1位置が必要です。このようにして、空のシーケンスを簡単に処理でき、何かが見つからない場合に返される明らかな結果があります。
  2. チェックする を見つけるための計算は、index非常に複雑です。必要なのは、検索するシーケンスの中間位置を見つけることだけです。はkey確かにこの計算の一部ではありません。
  3. シーケンスが空であるという状況に対処する必要があります。
  4. 個人的には、特に呼び出しが末尾再帰でない場合は、二分探索を再帰的に実装しません。
  5. 個人的な好みについて話すときは、とにかくイテレータの観点から実装します。
于 2013-08-25T02:19:29.930 に答える