1
私は確かに働くと感じたバブルソートのための機能を持っています。私はなぜ関数が単純にundefinedを返すのか分かりません。私はそれが再実行すべきかどうかをチェックしています。私のreRun変数がtrueに設定されている場合は再帰し、falseに設定されている場合は配列が返されます。なぜ私のバブルソート関数がelseをスキップして、未定義を返すのですか?
bubbleSort(array);
へ:あなたはこのラインにパッチを適用する必要が
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ループを試してみてください。 – georg
あなたは一度ループしすぎています: 'next = array [i + 1];'最後に 'undefined'を割り当てます。 – trincot
ちょっとした提案..次の配列[i + 1]がi
scaisEdge