【发布时间】:2016-12-27 13:43:28
【问题描述】:
我有一个冒泡排序功能,我觉得它肯定会起作用。我只是不明白为什么该函数只是返回未定义。我让它检查它是否应该重新运行。如果我的 reRun 变量设置为 true,那么它应该递归,如果它设置为 false,它应该返回数组。
这是我的代码:
var bubbleSort = function(array) {
// Your code here.
var tmp;
var next;
var curr;
var reRun = false;
console.log(reRun)
for(i = 0; i < array.length; i++){
// set curr var to current item and tmp to the next one
next = array[i+1];
// console.log('next', next)
curr = array[i];
// console.log('curr', curr)
// check to see if the curr value is greater than the nex
if(curr > next){
// if it is greater than set temp to be the next val and swap
// the two positions
array[i] = next
array[i+1] = curr;
reRun = true;
}
}
if(reRun === true){
bubbleSort(array)
} else if(reRun === false){
return array;
}
};
console.log(bubbleSort([2, 1, 3])); // yields [1, 2, 3]
【问题讨论】:
-
进行递归调用时,不要忘记返回它返回的任何内容:
return bubbleSort(array)。也就是说,这里不适合递归,请尝试使用 while 循环。 -
你循环的次数太多了:
next = array[i+1];分配了undefined最后一次。 -
只是一个建议.. 你应该检查 next = array[i+1] 仅在 i
-
很棒的反馈!我将尝试使用 while 循环。谢谢你们!