基本的に、二分探索の成功部分の値を画面に出力する方法を見つける必要があります。の初期値を変更しようとしましたlast
が、クラッシュするか、同じままです。コードをステップ実行したところ、すべてが正しく機能しているようです。
コンパイラからのプログラム サンプル
#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;
}