基本上我需要找出如何在屏幕上爲我的二進制搜索的成功部分輸出值。我試圖改變last
的初始值,但它崩潰或保持不變。我瀏覽了代碼,看起來一切正常。從編譯器C++中的二進制搜索
計劃樣品
#include<iostream>
using namespace std;
void binarySearch();
int main()
{
//Called the function in main
binarySearch();
system("pause");
return 0;
};
//void function for binary Search
void binarySearch()
{
//creating array
int array[100];
array[0] = 1;
int i,target;
// using Boolean to create pattern for generated numbers in the array
bool check = false;
//loop to implement pattern
for (int x = 1; x < 100; x++)
{
if (check == true)
{
array[x] = array[x - 1] + 1;
check = false;
}
else
{
array[x] = array[x - 1] + 2;
check = true;
}
}
**Code found online and modified to fit**
int first,mid,last,completed,successful,tests;
completed = 0;
successful = 0;
tests = 0;
double percentage;
percentage = 1;
for(int x=0;x<100;x++)
{
// Initialize first and last variables.
first = 0;
last = 2;
srand((unsigned)time(NULL));
int target = (rand() % 150) + 1;
while(first <= last)
{
mid = (first + last)/2;
if(target > array[mid])
{
first = mid + 1;
tests++;
}
else if(target < array[mid])
{
last = mid + 1;
tests++;
}
else
{
first = last - 1;
}
if(target == array[mid])
{
successful++;
}
}
completed++;
}
**Area which the error occur No value for successful**
//Output on screen
cout << endl;
cout << "There were "<< completed <<" searches completed."<< endl;
cout << "There were "<< successful <<" successful searches." << endl;
cout << percentage <<"%"<<" of the searches were successful." << endl;
cout << "There was an average of " << completed << " tests per search." << endl;
cout << endl;
}
如果你的'last'的初始值大約是要搜索的元素總數的某個地方,而不是2,那麼你可能會得到更好的結果。 – mah
好吧,我試着改變** last **的初始值,但它或者崩潰或保持不變。 –
你的問題是什麼? –