【发布时间】:2019-06-24 11:13:45
【问题描述】:
我正在编写一个代码,它基本上完成了一个主要问题。我写了一个二分搜索函数,返回找到的索引。每当我运行我的代码并搜索 2 的任何幂时,它都能正常工作。但是,每当我输入任何其他数字(例如 50)时,它都会返回错误。
在我的代码末尾,我有一个 else 语句,说明如果其他语句都没有返回值来返回 NULL,所以我遇到了一些麻烦。谢谢。我在 Xcode 和 UNIX 服务器上运行,但我注释掉了在 UNIX 服务器上运行的行。
#include <stdio.h>
#include <stdlib.h>
int* search(int* begin, int* end, int needle);
int main(int argc, char **argv) { //int argc = 1, char **argv array of char pointers
int num = 0;
int nums[10], i;
int *found = NULL;
if(argc != 2) {
printf("Enter a number to a power of 2 to search for:\n");
scanf("%d" , &num);
}
// num = atoi(argv[1]);
for(i = 0; i < 10; i++) { // initialzes array by shifting binary code to the left adding powers of 2
nums[i] = 1 << i; }
found = search(nums, &nums[9], num);
if(found) {
printf("Number %d found in index %ld.\n", num, found - nums);
}
else {
printf("Number %d was not found.\n", num);
}
return 0;
}
int* search(int* begin, int* end, int needle){
int *middle = (end-begin)/2 + begin;
if(*middle == needle){
return middle;
}
else if(needle < *middle){
end = middle;
return search(begin, end-1, needle);
}
else if(needle > *middle)
{
begin = middle;
return search(begin+1, end, needle);
}
else
return NULL;
}
我希望 main() 函数中的 else 语句在搜索到的值不在索引中时执行。
【问题讨论】:
标签: c algorithm pointers search binary