2015-11-05 29 views
-1

我嘗試使用遞歸在JavaScript中查找數組中的最大值。我創建了這個函數,但是不知道如何遞歸地執行它。以遞歸方式查找數組中的最大值

function Max(a) { 
    var a = [2,3,5]; 
    return Math.max.apply(Math, a); 
} 
+4

遞歸是調用它自己的函數。如果函數傳遞了數組值,那麼你想傳遞給內部函數調用的是什麼? –

+1

提示:max(a,b,c)= max(max(a,b),c)。 – mpen

+0

http://stackoverflow.com/questions/1379553/how-might-i-find-the-largest-number-contained-in-a-javascript-array –

回答

0

這裏是一個遞歸函數,它接受數字數組,並且比較在前兩個的例子,去除較小,然後將給定的陣列減去除去數目上再次調用自身。

function max(numArray) 
{ 
    // copy the given array 
    nums = numArray.slice(); 

    // base case: if we're at the last number, return it 
    if (nums.length == 1) { return nums[0]; } 

    // check the first two numbers in the array and remove the lesser 
    if (nums[0] < nums[1]) { nums.splice(0,1); } 
    else { nums.splice(1,1); } 

    // with one less number in the array, call the same function 
    return max(nums); 
} 

這裏有一個的jsfiddle:https://jsfiddle.net/t3q5sm1g/1/

+0

這將打破'[1,2,2,3]'(或任何兩個相鄰值相等的陣列) –

+0

哇耶已經更新,以處理這種情況 – thanksd

+0

這破壞了原始數組,使唯一的剩餘值是最大的。 – RobG

0
function max(array) { 
    if (array.length === 0) { // Step1: set up your base case 
     return array[0] 
} else { 
    return Math.max(array.shift(), max(array); // Step2: rec case 
} 
} 

每次遞歸情況稱爲它會更接近基本情況。

Math.max接受兩個數字,然後比較它們,然後返回兩個數字中較高的數字。

每次調用array.shift()時,都會從數組中彈出數組中的第一個元素,因此遞歸調用中的第二個參數是數組縮短一個。

當array.length只有一個元素時,返回該元素並觀察堆棧展開。