int i = 0;
int min = x[i];
while ( i < n ){
if ( x[i] < min ){
min = x[i];
}
i++;
}
return min;
I've written the iterative form to find the min number of an array. But I'd like to write a function that with recursion. Please help!
int i = 0;
int min = x[i];
while ( i < n ){
if ( x[i] < min ){
min = x[i];
}
i++;
}
return min;
I've written the iterative form to find the min number of an array. But I'd like to write a function that with recursion. Please help!
Because this sounds like homework, here's a hint: The minimum value in an array is either the first element, or the minimum number in the rest of the array, whichever is smaller.
The minimum number of a single-element array is the one element in the array.
The minimum number of an array with size > 1 is the minimum of the first element and the minimum of the rest of the array.
(The minimum number of an empty array is not defined.)
Why do you want to do this with recursion? A general rule with recursion is don't use recursion if you can do it inside a simple linear loop.
Sounds like homework, but your best bet is something like this:
int main(void) {
int size = 2;
int test[] = {0,1};
int min = test[0];
findMin(&min, test, size);
printf("%d", min);
}
void findMin(int* min, int* test, int* length);
void findMin(int* min, int* test, int* length) {
if (length >= 0) {
if (*test < *min) {
*min = test;
}
findMin(min, test++, (*length)--);
}
}
Here is a function that will return a pointer to the minimum value:
#include <stddef.h>
int *recursiveMin(int *x, int n) {
if (x == NULL || n == 0)
return NULL;
if (n == 1)
return x;
int *t = recursiveMin(x + 1, n - 1);
return *x < *t ? x : t;
}
Try:
int recursive_min(list<int> arr) {
return recursive_min(arr);
}
Although this doesn't work in imperative languages.
A more serious answer would be, in pseudocode:
func recursive_min( list l ) {
head = l[1]
tail = l[2<->end]
if l.length==1 return head else return min(head,recursive_min(tail))
}
Although that doesn't work if l is empty.
const int = 20;
int getmin (int v[], int n);
main ()
{ int v[N]; int i,n,min;
printf("\n\tType number of elements:\t"); scanf("%d",&n);
for (i=0;i }
min = getmin (v,n);
printf("\n\n\tMinimume value is %d.",min);
}
int getmin (int v[],int n)
{ if (n>0) {
if ( v[n-2] > v[n-1] )
{
v[n-2]=v[n-1];
}
getmin (v,n-1); }
return v[n-2];
}