Z
Z
Zhenia Bel2021-11-28 18:02:49
C++ / C#
Zhenia Bel, 2021-11-28 18:02:49

How to find the minimum element of an array using recursion?

How to find the minimum element of an array using recursion? here is my code:

#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <Windows.h>
#define N 100

int Min(int arr[], int n) {
  
}

int main()
{
  SetConsoleCP(1251);
  SetConsoleOutputCP(1251);
  srand(time(NULL));

  int arr[N], n;
  printf("n = ");scanf_s("%d", &n);
  for (int i = 0; i < n; i++)
  {
    arr[i] = rand() % 355;
    printf("%6d", arr[i]);
  }
  printf("\n");
  printf("Min = %d", Min(arr, n));
  return 0;
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexandroppolus, 2021-11-28
@Alexandroppolus

int Min(int arr[], int n, int current) {
  return n > 0 ? Min(arr, n - 1, min(current, arr[n-1])) : current;
}


int minValue = Min(arr, n, +бесконечность)

another option
int Min(int arr[], int n) {
  return n > 0 ? min(Min(arr, n - 1), arr[n-1])) : +бесконечность;
}


int minValue = Min(arr, n);

However, the first method is good because there is tail recursion, and the compiler can theoretically expand it into a loop.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question