ここに、特定のキーを見つけるために 100 個の整数の配列を検索するという非常に単純な仕事を行うプログラムがあります。このプログラムのlinearSearch
関数は再帰的であると想定されているため、関数自体から呼び出す必要があります。プログラムは正常にコンパイルされますが、何らかの理由で0
、入力した検索キーに関係なく、配列内の最初の要素のみが返されます。何が表示されないのですか? ありがとう。
#include <iostream>
using namespace std;
int linearSearch(const int[], int, int);
int main()
{
const int arraySize = 100; //size of array
int a[arraySize]; //create array a
int searchKey; //value to locate in array a
for(int i = 0; i < arraySize; i++)
a[i] = 2 * i; //create data
cout << "Enter integer search key: ";
cin >> searchKey;
//attempt to locate search key in array a
int element = linearSearch(a, searchKey, arraySize);
//display results
if(element != -1)
cout << "Found value in element: " << element << endl;
else
cout << "Value not found" << endl;
system("pause");
}
//linearSearch Function ****Returns 0 as index all the time *************
int linearSearch(const int array[], int key, int sizeOfArray)
{
static int index = 0;
//if Out of range, return -1 (Value not found)
if(index >= sizeOfArray){return -1;}
//if array value = key, array index is returned
if(array[index] == key){return index;}
//if array value is not equal to key, add to index and call func again
if(array[index] != key)
{
index++;
linearSearch(array, key, sizeOfArray);
}
}
index
と宣言することで正しいアプローチを取っていますよstatic
ね?
〜どうもありがとうございました。迅速で大変助かりました。=)