[英]Where is the flaw in my algorithm for constructing a sorted array of month-year dates given a min and a max?
[英]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.