0
我對編程頗爲陌生,而且遇到了一個問題。我正試圖對100個隨機整數進行二進制搜索。我把它們按降序排序。然而,我無法找到工作,我相信我可能不會完全理解它,(在課堂上錯過了那天,沒有筆記,在互聯網上工作)。任何幫助將不勝感激。我已經給了2 fcns。二進制和fcn我打電話給它。很抱歉,如果有很多代碼。在C++中實現二進制搜索
int binary_search(int random[], int low, int high, int search)
{
int index;
if (low > high)
index = -1;
else
{
int mid = (low + high)/2;
if (search == random[mid])
index = mid;
else
if (search < random[mid])
index = binary_search(random, low, mid - 1, search);
else
index = binary_search(random, mid + 1, high, search);
} // end if
return index;
}// end binarySearch
int randomizer(int random[]){
srand((unsigned)time(NULL));
ofstream PRINT("P4Output.txt");
const int arraySize = 100; //size of the array
int high = 100; // high for random numbers
int low = -100; // low for random numbers
int size = 0;
int out = 0;
random[arraySize]; // giving the array random 100 elements
int first = 0;
int last = 0;
int index = 0;
int search = 0;
cout << endl << " RANDOM: " << endl;
cout << " *************************************************" << endl << endl << endl;
PRINT << endl << " RANDOM: " << endl;
PRINT << " ************************************************" << endl << endl << endl;
for (int i = 0; i < 100; i++){ // Start of loop to insert 100 random values into array
random[i] = rand() % (high - low + 1) + low; //Inserting random values into array
cout << setw(5) << random[i]; // outputs the random integer with spacing.
PRINT << setw(5) << random[i];
if ((i + 1) % 10 == 0) {
cout << endl << endl << endl; // end of print line for set of 10 values
PRINT << endl << endl << endl;
}// end of if statement
} // End for-loop
cout << " SELECTION SORT: " << endl;
cout << " *************************************************" << endl << endl << endl;
PRINT << " SELECTION SORT: " << endl;
PRINT << " ************************************************" << endl << endl << endl;
selectionSort(random, arraySize); // calling selection sort
for (int j = 0; j < arraySize; j++){ // for-loop
cout << setw(5) << random[j]; //outputs integers w/ spacing
if ((j + 1) % 10 == 0){ // sets rows of ten
cout << endl << endl;
}
}// end of for-loop
cout << " BINARY SEARCH " << endl;
cout << " *************************************************" << endl << endl << endl;
PRINT << " BINARY SEARCH " << endl;
PRINT << " *************************************************" << endl << endl << endl;
index = binary_search(random, first, last, search);
for (int i = 0; i < arraySize; i++){
while (search != 101){
cout << "What number would you like to look for?" << endl;
cin >> search;
if (search == index)
cout << "found @" << index;
else
cout << "not found" << endl;
}
}
return out;
}
好了,所以修改後,我會打電話的正確方法?我只是在fcn中調用它,在arraySize上運行for循環,請求搜索值並執行if/else語句...?對不起,只是困惑。 – Squatch
你簡單的稱之爲參數建議:'binary_search(yourArrayName,0,100-1,numToSearchFor)'。 –
我也打電話給排序選擇,它必須分開。 – Squatch