gpt4 book ai didi

c - 二进制搜索c代码错误

转载 作者:行者123 更新时间:2023-11-30 16:41:17 26 4
gpt4 key购买 nike

这是我的二进制搜索代码。我想做的是当我放置一些东西(不在列表中)时显示“该数字不在列表中”。但效果不佳,我不知道为什么

int compare(int, int);

int binsearch(int list[], int searchnum, int left, int right);

int main() {


int right, left, middle;
int list[MAX_NUM] = { 1,3,5,7,9,11,13,15,17,19};

int searchnum,count=0;
int answer;
right = MAX_NUM-1;
left = 0;
printf("n : ");
scanf_s("%d", &searchnum);

answer=binsearch(list, searchnum, left, right);

if (answer == -1)
printf("%d is not in list", searchnum);
else
printf("%d", answer);

system("pause");
return 0;
}


int compare(int x, int y) {

if (x< y) return -1;
else if (x == y) return 0;
else return 1;

}


int binsearch(int list[], int searchnum, int left, int right) {

int middle;
while (left <= right) {
middle = (left + right) / 2;
switch (compare(list[middle], searchnum)) {
case -1: left = middle - 1;
break;
case 0: return middle;
case 1: right = middle - 1;

}
}
return -1;
}

最佳答案

您必须将 case -1: left = middle - 1; 更改为 case -1: left = middle + 1;
就像您所做的那样,您永远找不到比中位数更大的数字。

关于c - 二进制搜索c代码错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46297691/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com