c-在while条件本身内部实现一个打破while的if条件



我有这部分代码:

int arrayBinary_search(int myarray[], int key){
int selector;
int low_limit = 0;
int high_limit = SIZE;
while (1){
selector = (low_limit+high_limit)/2;
printf("The selector is: %dn", selector);
if (myarray[selector] == key){
return 1;
}
else {
if (low_limit==selector || high_limit==selector)
break;
if (key < myarray[selector])
high_limit = selector;
else
low_limit = selector;
printf("The high_limit is: %dn", high_limit);
printf("The low_limit is: %dn", low_limit);
}
}
}

此代码在数组中执行二进制搜索。它起作用,但while(1)不太好看。我想在while中实现一些条件来替换"1"。条件是如果在while循环内,则会破坏它。我尝试使用:while (!(low_limit==selector) && !(high_limit==selector)),但它在第一个循环后停止,因为在第一个周期后,"选择器"具有相同的值"high_limit"。

此处为完整代码。

当关键码:时,可以使用退出的do-while循环

int arrayBinary_search(int myarray[], int key)
{
int selector;
int low_limit = 0;
int high_limit = SIZE;
do {
selector = (low_limit + high_limit) / 2;
printf("The selector is: %dn", selector);
if (low_limit == selector || high_limit == selector)
return 0;
if (key < myarray[selector])
high_limit = selector;
else
low_limit = selector;
printf("The high_limit is: %dn", high_limit);
printf("The low_limit is: %dn", low_limit);
} while (myarray[selector] != key);
return 1;
}

另一方面,arrayGenerator函数不返回int,也不需要它,您可以将其设为void

最新更新