使用递归查找数组中的最大值

时间:2014-02-13 04:41:35

标签: recursion int max

这是我的测试数组

int [] A = {1,2,7,3,5,6};

这是方法

public static int largest(int [] A)
{
  int temp = A[0];
  return largestRec(A, 0, A.length - 1, temp);
}

// WRITE THIS METHOD that returns the largest of the elements in A
// that are indexed from low to high.  RECURSIVELY!
private static int largestRec(int [] A, int low, int high, int temp)
{  
  if (low == high)
    return A[low];

  if (low <= A.length){
    if (A[low] > temp){
      temp = A[low];
    }  
    largestRec(A, low+1, high, temp);      
  }   
  return temp
}

为什么tem会重置并返回A[0] 1

2 个答案:

答案 0 :(得分:0)

问题是你没有对largestRec的递归调用的返回值做任何事情。请记住,参数是按值传递的(即使在对同一函数的递归调用中),因此在函数内部更改它不会影响外部。

我认为你根本不应该将temp作为参数传递。

private static int largestRec(int [] A, int low, int high )
{ 
  int temp; 
  if (low == high)
    temp = A[low];
  else
  {
    temp = largetstRec( A, low+1, high );
    if (A[low] > temp){
      temp = A[low];
    }  
  }
  return temp;   
}

这使temp保持在函数的本地(我认为这可能是你首先称之为temp的函数。)

答案 1 :(得分:0)

private static int largestRec(int [] A, int low, int high){  
  var largest = A[low];

  if(low == high)
     return largest;  // or  A[high] because both are same

  for(var i = low; i < high; i++){
    if(largest < A[i])
      largest = A[i];
  } 

  return largest;
}