gpt4 book ai didi

c - 为什么我在二分搜索的实现中遇到段错误?

转载 作者:行者123 更新时间:2023-11-30 20:01:34 24 4
gpt4 key购买 nike

我目前正在尝试通过递归实现二分搜索并创建用户输入提示。每当我输入一个数字并搜索它时,我总是会遇到段错误(核心转储)。我在 CS50 设备中编写了此代码。

#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>
#include <ctype.h>
#include <string.h>


int findMidpoint(int min, int max);
int binarySearch(int key, int array[], int min, int max);


int main(int argc, string argv[])
{
int array[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23};
printf("Please search for a number : ");
int key = GetInt();
int search = binarySearch(key, &array, array[0], array[22]);
printf("Result: %i \n", search);
}

int findMidpoint(int min, int max)
{
int sum = min + max;
int mid = sum/2;

return mid;
}

int binarySearch(int key, int array[], int min, int max)
{
if(min > max)
{
return -1;
}
else
{
int midpoint = findMidpoint(min, max);

if(array[midpoint] < key)
{
binarySearch(key, array, midpoint+1, max);
}

else if(array[midpoint] > key)
{
binarySearch(key, array, midpoint-1, max);
}
else
{
return midpoint;
}

}

return -1;
}

最佳答案

这是经过一些修改后的代码:

#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>
#include <ctype.h>
#include <string.h>

int findMidpoint(int min, int max);
int binarySearch(int key, int array[], int min, int max);

int main(int argc, char** argv) {
int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
18, 19, 20, 21, 22, 23 };
printf("Please search for a number : ");
int key = GetInt();
int search = binarySearch(key, array, 0, 22);
printf("Result: %i \n", search);
}

int findMidpoint(int min, int max) {
int sum = min + max;
int mid = sum / 2;

return mid;
}

int binarySearch(int key, int array[], int min, int max) {
int midpoint = findMidpoint(min, max);
if (array[midpoint] < key) {
return binarySearch(key, array, midpoint + 1, max);
} else if (array[midpoint] > key) {
return binarySearch(key, array, min, midpoint - 1);
} else {
return array[midpoint];
}
return -1;
}

请注意,每次递归调用 binarySearch 时,您都需要返回结果。

关于c - 为什么我在二分搜索的实现中遇到段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30576016/

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