Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
492 views
in Technique[技术] by (71.8m points)

algorithm - find max and min of array c++ using recursion without changing function

I need help trying to find the min and max values in an array recursively in c++. the functions were given and cannot be changed.

I tried it out for both but for some reason nothing happens and the code does not enter the loop and I want to know what I am doing wrong. Here is my main and the min and max functions.

int main()
{
    int array[] = { 46, 22, 7, 58, 91, 55, 31, 84, 12, 78 };

    if (findMax(array, 10) == 91)
    {
        cout << "findMax is correct!" << endl;
    }

    if (findMin(array, 10) == 7)
    {
        cout << "findMin is correct!" << endl;
    }

    int findMax(int array[], int size)
    {
        int i = (size - 1);
        int max = 0;
        if (array[0] < array[i]) {
            max = array[i];
            findMax(array, size - 1);
        }
        return max;
        return 0;
    }

    int findMin(int array[], int size)
    {
        int i = 0;
        int j = size - 1;
        if (i == j) 
        {
            return array[i];
            i++;
        }

        int temp = findMin(array, size);

        if (array[i] < temp) 
        {
            return array[i];
        }

        else 
        {
            return temp;
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Well, you simply go backwards, return the min of each pair of elements and then next level make array size one smaller. Example:

int findMin(int array[], int n) 
{ 
    // if size = 0 means whole array has been traversed 
    if (n == 1){
        return array[0]; 
    }
    return min(array[n-1], findMin(array, n-1)); 
} 

And you can do the findMax using the same methodology.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...