C:为什么我的二分查找会陷入无限循环?
我有一个程序,它使用二分搜索来搜索文件(numbers.dat)并打印该值是否在数组中。目前,当我想搜索numbers.dat文件中的第一个值或不在numbers.dat文件中的值时,我会遇到无限循环,并且如果我想搜索文件中的任何其他值它打印索引和未找到消息。
这是我的代码:
int main() {
FILE *in_file; /* Input file */
int middle; /* Middle of our search range */
int low, high; /* Upper/lower bound */
int search; /* number to search for */
char line[80]; /* Input line */
in_file = fopen(DATA_FILE, "r");
if (in_file == NULL) {
fprintf(stderr,"Error:Unable to open %s\n", DATA_FILE);
exit (8);
}
/*
* Read in data
*/
max_count = 0;
while (1) {
if (fgets(line, sizeof(line), in_file) == NULL)
break;
/* convert number */
sscanf(line, "%d", &data[max_count]);
++max_count;
}
while (1) {
printf("Enter number to search for or -1 to quit:" );
fgets(line, sizeof(line), stdin);
sscanf(line, "%d", &search);
if (search == -1)
break;
low = 0;
high = max_count;
while (1) {
middle = (low + high) / 2;
if (data[middle] == search) {
printf("Found at index %d\n", middle);
}
if (low == high) {
printf("Not found\n");
break;
}
if (data[middle] < search)
low = (middle + 1);
else
high = (middle - 1);
}
}
return (0);
}
numbers.dat 文件的前几行是: 4 6 14 16 17 号 如果我搜索 4 或说 2,我会得到一个无限循环,如果我搜索 6,我会得到:
在索引 1 处找到
未找到
I have a program that searches a file (numbers.dat) using a binary search and prints whether the value is in the array or not. Currently, when I want to search for the first value in the numbers.dat file or for a value that is not in the numbers.dat file, I get an infinite loop, and if I want to search for any other value in the file it prints he index and Not found messages.
Here is my code:
int main() {
FILE *in_file; /* Input file */
int middle; /* Middle of our search range */
int low, high; /* Upper/lower bound */
int search; /* number to search for */
char line[80]; /* Input line */
in_file = fopen(DATA_FILE, "r");
if (in_file == NULL) {
fprintf(stderr,"Error:Unable to open %s\n", DATA_FILE);
exit (8);
}
/*
* Read in data
*/
max_count = 0;
while (1) {
if (fgets(line, sizeof(line), in_file) == NULL)
break;
/* convert number */
sscanf(line, "%d", &data[max_count]);
++max_count;
}
while (1) {
printf("Enter number to search for or -1 to quit:" );
fgets(line, sizeof(line), stdin);
sscanf(line, "%d", &search);
if (search == -1)
break;
low = 0;
high = max_count;
while (1) {
middle = (low + high) / 2;
if (data[middle] == search) {
printf("Found at index %d\n", middle);
}
if (low == high) {
printf("Not found\n");
break;
}
if (data[middle] < search)
low = (middle + 1);
else
high = (middle - 1);
}
}
return (0);
}
The numbers.dat file's first few lines are:
4
6
14
16
17
And if I search for 4 or say 2, I get an infinite loop and if I search for 6 I get:
Found at index 1
Not found
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
以下代码:
不退出循环。弄清楚你需要做什么才能摆脱这种情况。
The following code:
Does not exit the loop. Figure out what you need to do to get out of that.