【问题标题】:Why is my bubble sort function skipping over the else if and returns undefined?为什么我的冒泡排序函数会跳过 else if 并返回 undefined?
【发布时间】: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 循环。谢谢你们!

标签: javascript bubble-sort


【解决方案1】:

你必须修补这一行:

bubbleSort(array);

到:

return bubbleSort(array);

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

【讨论】:

    猜你喜欢
    • 2015-09-12
    • 2014-10-04
    • 2020-11-11
    • 2016-03-07
    • 2023-03-28
    • 1970-01-01
    • 2016-02-16
    • 2017-03-02
    • 1970-01-01
    相关资源
    最近更新 更多