Минимум массива с использованием рекурсии. Как это работает? - PullRequest
0 голосов
/ 04 ноября 2018

Может кто-нибудь объяснить, как работает приведенный ниже код?

int minElement(int arr[], int n) {
    if(n == 1)
        return arr[0];
    else {
        int m = minElement(arr, n-1);

        if(m < arr[n-1])
            return m;
        else
            return arr[n-1];
    }
}

1 Ответ

0 голосов
/ 04 ноября 2018

Я прокомментировал каждую строку

int minElement(int arr[], int n) {
   if(n == 1)  //When you reach the beginning of the array
        return arr[0]; // Return the first element
    else {
        int m = minElement(arr, n-1); // See what the minimum spot is below n-1 index

        if(m < arr[n-1]) // If the min element is below you return the min element
            return m;
        else
            return arr[n-1]; // If not return your value as the min element up until the index
    } // Repeat till you reach the top again
}

Надеюсь, это поможет

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...