Home > Net >  how to make recursive function that find the index of the biggest number in array?
how to make recursive function that find the index of the biggest number in array?

Time:07-19

I'm trying to find the index of the biggest number in array, by using a recursive function, but it doesn't work for me.

I wrote this code in "Online C Complier":

#include <stdio.h>
int max(int arr[], int n){
    if (n==0) {
        return 0;
    }
    int temp = max(arr, n-1);
    if (arr[temp] > arr[n]) {
        return temp;
    }
    else {
        return n;
    }
}

int main()
{
    int arr[] = {20,2,44,6,1,15,25,40};
    printf("The index is: %d\n", max(arr, 8));
    return 0;
}

The out put is sometimes 8 which is wrong and sometimes 2 which is correct.

thanks u all!

CodePudding user response:

For starters the first function parameter should have qualifier const because the passed array is not being changed within the function.

This part of the function

int temp = max(arr, n-1);
if (arr[temp] > arr[n]) {
    return temp;
}
else {
    return n;
}

is incorrect. For example n is not a valid index.

The function can look the following way as shown in the demonstration program below.

#include <stdio.h>

size_t max( const int arr[], size_t n )
{
    if ( n > 1 )
    {
        size_t i = max( arr   1, n - 1 )   1;
        return arr[0] < arr[i] ? i : 0;
    }
    else
    {
        return 0;
    }
}    

int main( void )
{
    int arr[] = { 20, 2, 44, 6, 1, 15, 25, 40 };
    const size_t N = sizeof( arr ) / sizeof( *arr );

    printf( "The index is: %zu\n", max( arr, N ) );
}

The program output is

The index is: 2

Or using your approach the function can look like

size_t max( const int arr[], size_t n )
{
    if ( n > 1 )
    {
        size_t i = max( arr, n - 1 );
        return !( arr[i] < arr[n-1] ) ? i : n - 1;
    }
    else
    {
        return 0;
    }
}
  • Related