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

时间:2013-10-24 03:25:03

标签: c++ c search recursion

我正在写一个递归二进制搜索程序。这是我到目前为止所得到的。该程序的参数是它包含2个函数,主函数和第二个函数,它将对它传递的值进行二进制排序。该程序有效,但它不会递归搜索该函数,我认为它不使用二进制搜索...

/* 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 */

2 个答案:

答案 0 :(得分:0)

你正在做的只是向后打印阵列,不是吗?您可以在http://en.wikipedia.org/wiki/Binary_search_algorithm中读取二进制搜索算法。我不明白为什么你说它必须&#34;是一个递归函数。我更喜欢二进制搜索的非递归函数,即使在维基百科链接中它也有递归方法。

答案 1 :(得分:0)

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

一旦你有一个已排序的数据集,你就试图找到一个遵循这种通用形式的函数(伪代码,而不是实际的C ++):

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)

确保处理弹出的任何边缘情况。特别要想想如果在大海捞针中找不到针头会发生什么。你可以添加一些处理这种情况的东西吗?