【问题标题】:Explain the recursion in this algorithm?解释这个算法中的递归?
【发布时间】:2016-10-04 15:07:26
【问题描述】:

我知道此算法用于查找任何数组的多数元素(如果有的话)。谁能解释一下递归调用?

if length(A) = 0 then
  return null
end if

if length(A) = 1 then
  return 1
end if

// "Command 7"
Call FIND-MAJORITY recursively on the first half of A, and let i be the result.

// "Command 8"
Call FIND-MAJORITY recursively on the second half of A, and let j be the result.

if i > 0 then
  compare i to all objects in A(including itself);
  let k be the number of times that equality holds;
  if k > length(A)/2 then
    return i.
  end if
end if

if j > 0 then
  compare j to all objects in A(including itself);
  let k be the number of times that equality holds;
  if k > length(A)/2 then
    return j
  end if
end if

return null

是否执行命令 7 直到它得到一个值……然后是命令 8?我无法理解这些递归。请举例说明,谢谢。

【问题讨论】:

    标签: recursion divide-and-conquer


    【解决方案1】:
    It depends what are inputs of this function.
    If the array A is an input then we only search in the diminished array else if the array A is defined as global then you always search the whole array.
    
    For example take the array A is 1,2,1,3,1,8,7,1
    
    If the array is given as input to the function : 
    
    According to recursion we get A is 1,2,1,3 -> A is 1,2 -> A is 1
    This returns i := 1.
    Then A is 2, this returns j:=1.
    Then we compare i to all elements of A i.e 1,2.
    Then we compare j to all elements of A i.e. 1,2.
    We return null from this recursive call.
    After this we proceed to upper recursion i.e. 1,2,1,3 and up to the first call.
    
    If the array is global:
    According to recursion we get A is 1,2,1,3 -> A is 1,2 -> A is 1
    This returns i := 1.
    Then A is 2, this returns j:=1.
    Then we compare i to all elements of A i.e. 1,2,1,3,1,8,7,1
    we return according to the conditions.
    
    **Remember even in this case we return all recursive calls and check the whole array for every recursive call which is not what you probably want.
    

    【讨论】:

      猜你喜欢
      • 2021-11-04
      • 2022-07-04
      • 1970-01-01
      • 1970-01-01
      • 2018-02-26
      • 1970-01-01
      • 1970-01-01
      • 2011-01-19
      • 1970-01-01
      相关资源
      最近更新 更多