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
1.2k views
in Technique[技术] by (71.8m points)

algorithm - Find maximum value in an array by recursion

// Find a maximum element in the array.
findMax(A)
   findMaxHelper(A, 0, A.length)

findMaxHelper(A, left, right)
   if (left == right - 1) 
      return A[left]
   else
      max1 = findMaxHelper(A, left, (right + left) / 2)
      max2 = findMaxHelper(A, (right + left) / 2, right)

      if (max1 > max2) 
         return max1 
      else 
         return max2

I am having a hard time understanding what is happening in this pseudo-code.

Can someone help explain what is happening at each line. I need to understand this code before I can answer the questions.

I know that the function findMax calls the helper function findMaxHelper, then findMaxHelper uses recursion. Other than that, I really don't understand it.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You are using Divide and Conquer algorithm for finding the maximum element from the array. First, you are dividing the array into individual elements (divide), then you are comparing the elements (conquer). You are dividing the array using calling findMaxHelper recursively.

The general idea of Divide and conquer is shown in the figure:

enter image description here

Example:

enter image description here Here max is same as your findMaxHelper function with two arguments i.e. left and right.

Check this example for more in depth understanding of the concept.


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

...