Search code examples
carraysalgorithmsortingdivide-and-conquer

Divide and Conquer-Returning an array


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

Solution

  • 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