为什么我的冒泡排序函数会跳过 else if 和 returns undefined?

Why is my bubble sort function skipping over the else if and returns undefined?

我有一个冒泡排序函数,我觉得它肯定会起作用。我只是不明白为什么函数只是 return 未定义。我让它检查它是否应该重新运行。如果我的 reRun 变量设置为 true,那么它应该递归,如果它设置为 false,它应该 return 数组。

这是我的代码:

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]

你必须修补这一行:

bubbleSort(array);

至:

return bubbleSort(array);

这样做的原因是,结果仅由对 bubbleSort 的最终调用返回,它永远不会通过所有先前的调用向上传播堆栈,因为您不会从这些调用中返回任何内容。