簡體   English   中英

查找數組最大元素的算法的缺陷在哪里?

[英]Where is the flaw in my algorithm for finding the max element of an array?

為了更聰明,我嘗試遞歸地編寫每個算法,即使非遞歸解決方案更易讀和高效(例如“ Hello,World!”的情況)。 我以一個簡單的max函數開始

function max ( arr )
{
     max_in_bounds(arr,0,arr.length);
}

function max_in_bounds ( A, i, j )
{
      // finds the max element in the range of 
    // indices [i, j) of the array A
    var diff = j - i;
    if ( diff === 1) 
    {
          return A[i];  
    }
    else if ( diff > 1 ) 
    {
             return Math.max(A[i], max_in_bounds(A,i+1,A.length));      
    }
}

var my_array = [1, 4, -3, 69]; 
console.log(max(my_array)); // Should print 69

但是由於某種原因,我變得undefined並且試圖找出原因。 有什么提示嗎?

該函數沒有返回值:

function max ( arr ){
     return max_in_bounds(arr,0,arr.length);
}

因此它返回undefined 我也希望您僅出於學習目的而編寫所有這些遞歸算法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM