【发布时间】:2018-03-07 03:49:42
【问题描述】:
我正在尝试使用递归进行二进制排序功能。它适用于 list[] 结构数组中存在的值。但是,当我输入一个我知道不在数组内的值时,它不是返回 -1,而是返回垃圾值。我在 MVS 中使用调试器跟踪了代码,但可能(事实上,肯定是)一些我看不到的东西。
谁能告诉我为什么它不返回 -1?
#include<stdio.h>
#include<string.h>
#define MAX 20
typedef struct
{
char name[MAX] = "";
char surname[MAX] = "";
int id;
}patient;
int binarySearch(patient list[], char *target, int top, int bottom, int *comparisons)
{
int center;
center = (top + bottom) / 2;
if (strcmp(list[center].surname, target) == 0)
return center;
(*comparisons)++;
if (top == center || bottom == center)
return -1;
if (strcmp(list[center].surname, target) == 1)
return binarySearch(list, target, center - 1, bottom, comparisons);
if (strcmp(list[center].surname, target) == -1)
return binarySearch(list, target, top, center + 1, comparisons);
}
int main(void)
{
FILE *fi = fopen("patients.txt", "r");
if (fi == NULL)
printf("Problem opening file!");
else
{
patient list[MAX];
int i = 0, comparisons = 0, index;
char target[MAX] = "";
while (fscanf(fi, "%s %s %d", &list[i].name, &list[i].surname, &list[i].id) != EOF)
i++;
printf("Enter the surname of the patient (END to exit): ");
scanf("%s", target);
index = binarySearch(list, target, i, 0, &comparisons);
printf("%-15s %-15s %-15d\n", list[index].name, list[index].surname, list[index].id);
printf("%d comparisons\n", comparisons);
}
}
【问题讨论】:
-
通常,您必须提供 MCVE。请参阅网站指南,了解有关主题或离题的更多信息。
-
@UlrichEckhardt 你好。老实说,我认为这个问题有点 MCVE,但我完全可能是错的。请您指出您的建议,使其更合适,以便我尽快提供?
-
要成为 MCVE,人们应该能够编译和运行您提供的内容,并让输出确认您陈述的问题。就目前而言,我不得不猜测你做了什么来驱动它并编写更多代码来运行它。
-
@pjs 哦。我认为发布整个代码会很浪费。让我更新一下问题。
-
取决于“整个代码”是什么。 MCVE 的“最小”部分提供了足够的代码来说明问题。
标签: c recursion binary-search