【问题标题】:Divide and Conquer-Returning an array分而治之——返回数组
【发布时间】:2018-01-26 20:29:22
【问题描述】:

我最近正在研究分而治之算法。

如果返回值假设为某个整数,我就能解决问题。

例如:1。二分查找,这里只要找到就返回1,否则返回-1。

例如:2。数组中的最大个数,只需要返回一个数字即可。

但是当涉及到返回一个数组时,比如我们需要整个数组作为输出(例如:排序)。

我觉得很难。

任何人都可以提供最佳方法吗?

以下是我的二分搜索方法。

#include<stdio.h>
char* Divide(int arr[],int l,int r,int key)
{
    int m=(l+r)/2;
    if(l==r)
    {
        if(key==arr[m])
            return "Found";
        else
            return "Not Found";
    }
    else
    {
        if(key==arr[m])
            return "Found";
        else if(key>arr[m])
            Divide(arr,m+1,r,key);
        else
            Divide(arr,l,m,key);
    }
}
int main()
{
    int arr[]={1,2,3,4,5,6,7,8};
    int n=sizeof(arr)/sizeof(arr[0]);
    char* result=Divide(arr,0,n-1,10);
    printf("%s\n",result);
    return 0;
}

【问题讨论】:

  • 您对Divide 的递归调用不会返回任何内容。这会导致未定义的行为
  • 另外,请花一些时间到read about how to ask good questions。您的问题缺乏信息,例如您显示的代码有什么问题?我还建议您阅读 Eric Lippert 的 How to debug small programs,并学习如何使用调试器。
  • 函数结束时隐式返回,所以是否需要调用return指令。
  • 如果你声明一个函数返回一个值(即它的返回不是void),你必须显式返回具有正确类型的东西,否则你将拥有undefined behavior,这会使你的整个程序格式错误且无效。

标签: c arrays algorithm sorting divide-and-conquer


【解决方案1】:

您必须在递归调用尝试中返回值

#include<stdio.h>
char* Divide(int arr[],int l,int r,int key)
{
    int m=(l+r)/2;
    if(l==r)
    {
        if(key==arr[m])
            return "Found";
        else
            return "Not Found";
    }
    else
    {
        if(key==arr[m])
            return "Found";
        else if(key>arr[m])
            return Divide(arr,m+1,r,key); // just returning values here
        else
            return Divide(arr,l,m,key); // and here would make it work
    }
}
int main()
{
    int arr[]={1,2,3,4,5,6,7,8};
    int n=sizeof(arr)/sizeof(arr[0]);
    char* result=Divide(arr,0,n-1,10);
    printf("%s\n",result);
    return 0;
}

online compiler查看演示

【讨论】:

    猜你喜欢
    • 2017-06-08
    • 2017-06-21
    • 2013-01-16
    • 1970-01-01
    • 2013-11-09
    • 2017-06-07
    • 1970-01-01
    • 2013-01-31
    • 2016-05-01
    相关资源
    最近更新 更多