2

I'm Recently going through Divide and Conquer Algorithm.

I'm able to solve the problems if the return value supposes to be some single integer.

Ex:1. Binary Search, here I just need to return 1 if found, else -1.

Ex:2. Maximum Number in an array, just need to return a single number.

But when it comes to returning an array, like when we need the whole array as output(Ex: Sorting).

I feel it difficult.

Can anyone help with the best approach?

Below is my approach for Binary Search.

#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;
}
SanQA
  • 233
  • 3
  • 9
  • Your recursive calls of `Divide` doesn't return anything. That leads to *undefined behavior*. – Some programmer dude Aug 18 '17 at 08:17
  • Also, please take some time to [read about how to ask good questions](http://stackoverflow.com/help/how-to-ask). Your question is lacking information, like saying what is wrong with the code you show? I also recommend you read [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) by Eric Lippert, and learn how to use a debugger. – Some programmer dude Aug 18 '17 at 08:23
  • When the function ends, it implicitly returns, so is there a need to call the return instruction. – SanQA Aug 18 '17 at 09:29
  • If you declare a function to return a value (i.e. its return is not `void`) you must explicitly return something with the correct type, or you will have [*undefined behavior*](https://en.wikipedia.org/wiki/Undefined_behavior) which makes your whole program *ill-formed* and invalid. – Some programmer dude Aug 18 '17 at 09:33

1 Answers1

1

you would have to return the values in your recursive call try

#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;
}

check the demo at online compiler

marvel308
  • 10,288
  • 1
  • 21
  • 32