简体   繁体   中英

Multipath recursion Maximum Value in Array

I am having trouble writing a multipath recursive function given an unsorted integer array.

std::max(maxArray(a[],first,last))

I understand that I need to split the arrays in half and use the std::max function that compares two integers such as:

return std::max(maxArray(a[],Not sure, Not Sure),maxArray(a[], Not sure, Not sure))

I am familiar with the Binary Search Algorithm. However, I am struggling to see how I can solve this without just comparing the two numbers from the left and right side of the array. Won't those two numbers just return the greater of the 2 compared and then get trashed?

I have seen the other posts about this same problem however it does not adhere to the pseudocode that was given. Any help would be greatly appreciated.

I'm struggling to understand your explaination of what it is you don't understand. But the principle behind the code you've been given is that if you divide an array into two halves and find (recursively) the maximum value in each half, then the maximum value for the whole array is the larger of those two values.

Something like this

int maxArray(const int* a, int left, int right)
{
    if (left == right)
    {
        return a[left];
    }
    else
    {
        int mid = (left + right)/2;
        return std::max(
            maxArray(a, left, mid),
            maxArray(a, mid + 1, right));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM