c - Divide and Conquer-Returning an array -
i'm going through divide , conquer algorithm.
i'm able solve problems if return value supposes single integer.
ex:1. binary search, here need return 1 if found, else -1.
ex:2. maximum number in array, need return single number.
but when comes returning array, when need whole array output(ex: sorting).
i feel difficult.
can best approach?
below approach 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; }
you have return values in 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); // returning values here else return divide(arr,l,m,key); // , here make 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 demo @ online compiler
Comments
Post a Comment