Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 将我的二进制搜索程序改进为递归程序?_C++_C_Search_Recursion - Fatal编程技术网

C++ 将我的二进制搜索程序改进为递归程序?

C++ 将我的二进制搜索程序改进为递归程序?,c++,c,search,recursion,C++,C,Search,Recursion,我正在写一个递归二进制搜索程序。这是我到目前为止得到的。这个程序的参数是,它包含两个函数,主函数和第二个函数,这两个函数将对传递的值进行二进制排序。这个程序可以运行,但它不会递归地搜索函数,我认为它也不会使用二进制搜索 /* ex06_18.c */ #include <stdio.h> #define SIZE 10 /* function prototype */ void someFunction( const int b[], int startIndex, int siz

我正在写一个递归二进制搜索程序。这是我到目前为止得到的。这个程序的参数是,它包含两个函数,主函数和第二个函数,这两个函数将对传递的值进行二进制排序。这个程序可以运行,但它不会递归地搜索函数,我认为它也不会使用二进制搜索

/* ex06_18.c */
#include <stdio.h>
#define SIZE 10

/* function prototype */
void someFunction( const int b[], int startIndex, int size );

/* function main begins program execution */
int main( void )
{
int a[ SIZE ] = { 8, 3, 1, 2, 6, 0, 9, 7, 4, 5 }; /* initialize a */
printf( "Answer is:\n" );
someFunction( a, 0, SIZE );
 printf( "\n" );
return 0; /* indicates successful termination */
}
void someFunction( const int b[], int startIndex, int size )
{
if ( startIndex < size ) {
someFunction( b, startIndex + 1, size );
printf( "%d ", b[ startIndex ] );
} /* end if */
} /* end function someFunction */
/*ex06_18.c*/
#包括
#定义尺寸10
/*功能原型*/
void someFunction(const int b[],int startIndex,int size);
/*函数main开始执行程序*/
内部主(空)
{
int a[SIZE]={8,3,1,2,6,0,9,7,4,5};/*初始化a*/
printf(“答案是:\n”);
someFunction(a,0,SIZE);
printf(“\n”);
返回0;/*表示成功终止*/
}
void someFunction(常量int b[],int startIndex,int size)
{
如果(开始索引<大小){
someFunction(b,startIndex+1,size);
printf(“%d”,b[startIndex]);
}/*如果结束*/
}/*结束函数*/

您所做的只是向后打印阵列,不是吗?您可以在中读取二进制搜索算法。我看不出你为什么说它“必须”是一个递归函数。我更喜欢二进制搜索的非递归函数,即使在wikipedia链接中它也有递归方法。

二进制搜索仅在数据集排序时有效;否则,“小于”和“大于”比较是完全无用的,因为它们不会告诉您任何其他元素的位置。因此,首先,您需要确保数据集已排序,这是一个单独的问题

一旦您有了一个排序的数据集,您将尝试生成一个遵循以下一般形式的函数(伪代码,而不是实际的C++):

功能搜索(针、草垛、开始、结束){
int middle_idx=haystack[(开始+结束)/2]
if(草垛[中间的idx]==针)
返回中间_idx;
否则如果(干草堆[中间]
返回搜索(针、干草堆、开始、中间)
else if(干草堆[中间的idx]>针)
返回搜索(针、草垛、中间_idx+1、结束)
确保处理任何弹出的边缘情况。特别是,想想如果大海捞针不见踪影会发生什么;你能添加一些处理这种情况的东西吗?

“程序工作”——除非你对“搜索”的概念与其他人完全不同。“它不会递归搜索函数”--只是因为它不搜索;很明显,它是递归的。“我不认为它使用二进制搜索”--你不这么认为吗?你是否跳过了课堂上的讨论,没有阅读关于这个主题的教科书?即使如此,谷歌上也有大量的参考资料。“二进制排序”--等等,现在要排序吗?排序、搜索和打印所有值是三件不同的事情。
function search(needle, haystack, start, end) {
    int middle_idx = haystack[(start+end)/2]
    if(haystack[middle_idx] == needle)
        return middle_idx;
    else if(haystack[middle_idx] < needle)
        return search(needle, haystack, start, middle_idx-1)
    else if(haystack[middle_idx] > needle)
        return search(needle, haystack, middle_idx+1, end)