Coder117
Coder117

Reputation: 851

How to recursively find the index of a max element in C++?

It doesn't seem too hard to get the max value:

int getMax(int arr[], int size) {
    if(size == 1) {
        return arr[0]
    }
    return max(arr[size - 1], getMaxIndex(arr, size - 1));
}

But how can I find the index of where it was at? If I create a count variable it will just get wiped as soon I recursively call. I can't find anywhere online where someone does this recursively with only the array and a size parameter. Thanks for any help.

Upvotes: 1

Views: 995

Answers (1)

Jarod42
Jarod42

Reputation: 217408

You might do it like that:

int getMaxIndex(int arr[], int size) {
    if (size == 1) {
        return 0;
    }
    const auto recMaxIndex = getMaxIndex(arr, size - 1);
    if (arr[recMaxIndex] < arr[size - 1]) {
        return size - 1;
    } else {
        return recMaxIndex;
    }
}

Upvotes: 5

Related Questions