因此,我有一个二进制搜索代码(不是我的),并且我不知道如何对它进行的比较次数计数。 输入元素然后进行排序。 然后出现此代码。
System.out.println("\nEnter value to find");
num_search = in.nextInt();
first = 0;
last = n - 1;
middle = (first + last)/2;
while( first <= last )
{
if ( a[middle] < num_search )
first = middle + 1;
else if ( a[middle] == num_search )
{
System.out.println(num_search + " found at location " + (middle + 1) + ".");
System.out.println("Counter = " + (ctr + middle));
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if (first > last)
System.out.println(num_search + " isn't present in the list.\n");
答案 0 :(得分:0)
您可以像这样增加计数:
?cbind
答案 1 :(得分:0)
对于所有三种情况,只需增加ctr
的值即可。
确保已使用ctr
初始化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");