Data Structures Discussion Post

jpFlute

Recursive Thinking

Please discuss how to find the largest element in an array by thinking recursively.

 

and

 

Reply to these two peer posts.

 

From Ted

 

The most logical way for me to find the largest element in an array is by thinking logically and developing an algorithm that would find exactly the former. For me that would involve using an algorithm that went through each arrayed item one at a time to determine the largest of the elements [i+1]. Something similar to:

int max(int lgArr[], int size, int lg, int i){

if (i < size){

if(lg < lgArr[i])

max=arr[i];

max(lgArr, size, lg, i+1);

}

return max;

}

 

 

From Bill

 

A function is recursive if it is called multiple times, to find the largest element in an arrayrecursively. We simply create a function that will call its self a number of times until the max is found. For instance with the example below the function calls itself four time seeking the largest number.  Through searching the web there are multiple ways to work through this problem, however if dealing with a large amount of data this would not necessarily be an effective means.

Chris

int maxArray(int myArray[5], int size)

{

                if (size == 1)

                                return myArray[0];

                else

                {

                                if (maxArray(myArray, size - 1) > myArray[size - 1])

                                                return maxArray(myArray, size - 1);

                                else

                                                return myArray[size - 1];

                }

}

 

int main()

{

                int array[5] = { 5, 15, 25, 10, 20 };

 

                cout << "The largest value is: " << maxArray(array, 5) << endl;

 

                system("PAUSE");

                return 0;

}

    • 10 years ago
    • 20
    Answer(1)

    Purchase the answer to view it

    NOT RATED
      Bids(1)