【发布时间】:2022-12-13 10:44:33
【问题描述】:
所以我正在学习关于排序数组和 while 循环的 c,我正在学习的书中的代码:
//function to perform binary search of an array
size_t binarySearch(const int b[], int searchKey, size_t low, size_t high)
{
//loop until low index is greater than high index
while (low <= high) {
//determine middle element of subarray being searched
size_t middle = (low + high) / 2;
//display subarray used in this iteration
printRow(b, low, middle, high);
// if searchKey matched middle element, return middle
if (searchKey == b[middle]) {
return middle;
}
// if searchKey is less than middle element, set new high
else if (searchKey < b[middle]) {
high = middle - 1; //search low end of array
}
else {
low = middle + 1; //search high end of the array
}
}//end while
return -1; //searchKey not found
}
问题是我不知道初始 while 条件是如何工作的”而(低 <= 高)“,我的意思是低永远不会大于高,谁能告诉我在什么情况下低会大于高,从而终止循环?
我试图写下并形象化算法的工作原理,但无法理解
【问题讨论】:
-
整数除法错误可能导致
middle + 1(低)大于middle - 1(高)(即使分配这些值的语句由排他性 if 块分隔)从而满足退出条件 -
low能够变得大于high:low = middle + 1;。如果low是(例如)5 而high是 5,那么low就变成 6。
标签: c loops search while-loop