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

Categories

// 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.2k views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...