2014-02-13 73 views
0

數組查找最大值這是我的測試陣列使用遞歸

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

回答

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擺在首位)。

+0

感謝這解決了一切。 – user3247435

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; 
} 
+0

這需要是遞歸方法,因此不允許循環 – user3247435