2 回答
TA贡献1801条经验 获得超8个赞
简单地增加ctr所有三种情况的值。确保您已初始化ctrwith 0;
while( first <= last )
{
if ( a[middle] < num_search )
{first = middle + 1;
ctr++; //<----increment the count by 1
}
else if ( a[middle] == num_search )
{
ctr++; //<----increment the count by 1
System.out.println(num_search + " found at location " + (middle + 1) + ".");
System.out.println("Counter = " + ctr); //<-----add 1 to result
break;
}
else
{last = middle - 1;
ctr++; //<----increment the count by 1
}
middle = (first + last)/2;
}
if (first > last)
System.out.println(num_search + " isn't present in the list.\n");
TA贡献1898条经验 获得超8个赞
您可以像这样增加计数:
int count = 0;
while( first <= last )
{
if ( a[middle] < num_search ) {
count+= 1;
first = middle + 1;
}
else if ( a[middle] == num_search )
{
count+= 2;
System.out.println(num_search + " found at location " + (middle + 1) + ".");
break;
}
else {
count+= 3;
last = middle - 1;
}
middle = (first + last)/2;
}
System.out.println("Counter = " + count);
添加回答
举报