How can you find the minimum value in an array using recursion?

I need to write C code that finds the smallest value in an array using recursion. I already did this using a for loop, but recursion is harder. Can someone help me?

-3
source share
5 answers

Here is a simple code to find the minimum value using recursion,

int rec(int a[],int n) { int min; if(n==1) return a[0]; else { min=rec(a,n-1); if(min<a[n-1]) return min; else return a[n-1]; } } void main() { int i,j,n,a[20]; printf("enter n :"); scanf("%d",&n); printf("enter values : "); for(i=0;i<n;i++) { scanf("%d",&a[i]); } printf("\n%d",rec(a,n)); getch(); } 
0
source
  • The smallest array of elements is the only element (base case or termination condition).

  • The minimum array is the minimum [first element, the minimum of the rest (excluding the first element)]

+4
source
 #include <stdio.h> int minimum(int *a_s, int *a_e, int candidate){ if(a_s == a_e) return candidate; return minimum(a_s+1, a_e, *a_s < candidate ? *a_s : candidate); } int main(void){ int array[] = { 1,3,-2,0,-1}; printf("%d ", minimum(array+1, &array[sizeof(array)/sizeof(*array)], *array)); return 0; } 
+1
source

After accepting the answer.

Below is a recursive solution that does not chew on the stack. Estimate the maximum stack depth on O (ln2 (n)). Other solutions look like maximum stack depth O (n).

 int ArrayMin(const int a[], size_t n) { if (n <= 1) { if (n < 0) return 0; // Handle degenerate ArrayMin( ,0) return a[0]; } size_t nhalf = n / 2; int left = ArrayMin(a, nhalf); int right = ArrayMin(&a[nhalf], n - nhalf); return left < right ? left : right; } 

Answered after 9 hours, we can assume that the deadline for completing homework has already passed.

+1
source
  • Consider that the first element of the array is minimal.
  • Call a function by passing the base address of the array and the number of elements.
  • Check any other number less than the minimum value, if so assign this value to the minimum.
  • For each iterative increment, the address of the array and the decrement of no elements!

Try this code -

 #include<stdio.h> int min; int arrfun(int *arr,int n) { if(n){ if(*arr < min) // check any no is less than minimum. min = *arr; // if yes assign it } else return min; // when n becomes 0 it returns the minimum element arrfun(++arr,--n); // recursive call } int main() { int arr[]={7,3,9,2,1,6}; min = arr[0]; // Taking first element is minimum printf("minimum is: %d\n",arrfun(arr,6)); // call the function by passing address and no of elements in array return 0; } 
0
source

Source: https://habr.com/ru/post/1432527/


All Articles