[英]counting comparisons in a binary search function
我正在运行这个二进制搜索 function 并且我正在努力运行一个增量器来计算已进行的比较量。
我想在最后一个 cout 语句(为空)中与 output 进行比较的次数。 有人可以指出我正确的方向吗?
void binarySearch( int nums[], int size)
{
int first = 0; //first array elements
int last = size - 1; //last array
int middle; //midpoint of search
int position = -1; //position of search value
bool found = false; //flag
for (int j = 1; j < 4; j++)
{
int randVal = rand() % size + 1; //rand value to be searched
while (!found && first <= last)
{
middle = (first + last) / 2; //calculate midpoint
if( nums[middle] == randVal) //if value is at mid
{
found = true;
position = middle;
}
else if (nums[middle] > randVal) //if value is in lower half
{ last = middle - 1; }
else
{ first = middle + 1; } //if value is in upper ha;f
}
cout << "|Run " << j << ": " << endl;
cout << " -Search: " << randVal << "\n"; //cout searched value
cout << " -Comparisons: " << "\n\n"; //cout # of comparisons that were made
}
}
void binarySearch( int nums[], int size)
{
int first = 0; //first array elements
int last = size - 1; //last array
int middle; //midpoint of search
int position = -1; //position of search value
bool found = false; //flag
for (int j = 1; j < 4; j++)
{
int comp = 0;
int randVal = rand() % size + 1; //rand value to be searched
while (!found && first <= last)
{
comp++;
middle = (first + last) / 2; //calculate midpoint
if( nums[middle] == randVal) //if value is at mid
{
found = true;
position = middle;
}
else if (nums[middle] > randVal) //if value is in lower half
{ last = middle - 1; }
else
{ first = middle + 1; } //if value is in upper ha;f
}
cout << "|Run " << j << ": " << endl;
cout << " -Search: " << randVal << "\n"; //cout searched value
cout << " -Comparisons: " << comp << "\n\n"; //cout # of comparisons that were made
}
}
注意:如果您不需要最终比较(找到的值),您可以从 -1 而不是 0 开始 comp。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.