【问题标题】:improve my binary search program to a recursive one?将我的二进制搜索程序改进为递归程序?
【发布时间】:2013-10-24 03:25:03
【问题描述】:

我正在编写一个递归二进制搜索程序。这是我到目前为止所得到的。该程序的参数是它包含 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 */

【问题讨论】:

  • “程序有效”——除非你对“搜索”的概念与其他人完全不同。 “它不递归搜索函数”——只是因为它不搜索;显然,它是递归的。 “我不认为它使用二进制搜索”——你不这么认为吗?您是否跳过课堂讨论,没有阅读有关该主题的教科书?即使是这样,也可以通过 google 获得大量参考资料。 “二元排序”——等等,现在你要排序吗?排序、搜索和打印所有值是三件不同的事情。

标签: c++ c search recursion


【解决方案1】:

您所做的只是向后打印数组,不是吗?您可以在http://en.wikipedia.org/wiki/Binary_search_algorithm 中阅读二进制搜索算法。我看不出你有什么理由说它“必须”是一个递归函数。我更喜欢二进制搜索的非递归函数,即使在维基百科链接中它也有递归方法。

【讨论】:

    【解决方案2】:

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

    一旦你有了一个排序的数据集,你就试图想出一个遵循这种一般形式的函数(伪代码,而不是实际的 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)
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多