2014-03-31 47 views
0

我正在用JavaScript实现冒泡排序的方法,这是我目前的代码:未定义的错误,而使用array.length

// Sort array (ascending) 
function sort(array) { 

    var sortedArray = array; 
    // This swapped 'flag' tells the function whether or not it will 
    // need to iterate over the array again to continue sorting 
    var swapped = false; 

    for(var i = 1; i < array.length; i++) { 
    var prev = array[i - 1]; 
    var current = array[i]; 

    // If the previous number is > than the current, swap them around 
    if(prev > current) { 
     swapped = true; 

     sortedArray[i] = prev; 
     sortedArray[i - 1] = current; 
    } 

    } 
    // If there has been a swap, sort over the array again 
    if(swapped) { 
    return sort(); 
    } 

    return sortedArray; 
} 


var testArray = [1, 4, 27, 3, 2]; 


// Run the sort function 
sort(testArray); // [1, 2, 3, 4, 27] 

当我运行它,我不断收到“无法读取的性能。长度undefined'

但是,我可以在for循环之前调用console.log(array.length)并返回一个值。

这是我的代码repl.it

为什么我得到'undefined'?

+6

'返回排序(阵列)''不返回排序()'? – Andy

+0

谢谢安迪,就是这样!我想在尝试其他事情之前我需要周一早上的咖啡。再次感谢! – HelloWorld

回答

2

按我的意见:你需要在array再次传递给排序函数:

if (swapped) { 
    return sort(array); 
} 
+1

把这个标记为答案,给这个家伙一些信用^ _ ^ – weeknie

0
// If there has been a swap, sort over the array again 
    if(swapped) { 
    return sort(); 
    } 

你在这里没有参数返回sort()。