【问题标题】:Selection sort returning undefined [closed]选择排序返回未定义[关闭]
【发布时间】:2020-06-23 10:05:28
【问题描述】:

我正在尝试在 Javascript 中实现选择排序算法,但它返回未定义。我尝试了很多次彻底查看,但无法找出错误。

这是我的代码:

const selectionSort = (arr) => {
  let smallest;
  let len = arr.length;
  for (let i = 0; i < len; i++) {
    smallest = i;
    for (j = i + 1; j < len; j++) {
      if (arr[smallest] > arr[j]) {
        smallest = j;
      }
    }

    let temp = arr[i];
    arr[i] = arr[smallest];
    arr[smallest] = temp;
  }
  return smallest;
};
console.log(selectionSort[(3, 2, 4, 1)]);

【问题讨论】:

  • 您在拨打selectionSort()之后切换了方括号和圆括号

标签: javascript algorithm ecmascript-6


【解决方案1】:

我觉得你说错了


console.log(selectionSort([3, 2, 4, 1]));

函数将数组作为输入。

const selectionSort = (arr) => {
    let smallest;
    let len = arr.length;
    for (let i = 0; i < len; i++) {
      smallest = i;
      for (j = i + 1; j < len; j++) {
        if (arr[smallest] > arr[j]) {
          smallest = j;
        }
      }
  
      let temp = arr[i];
      arr[i] = arr[smallest];
      arr[smallest] = temp;
    }
    return arr;   //return array here if you want full array
  };
  console.log(selectionSort([3, 2, 4, 1]));

【讨论】:

  • 谢谢,打错字了。并返回最小的而不是数组。感谢您的帮助,非常感谢。
猜你喜欢
  • 2014-10-29
  • 1970-01-01
  • 2020-11-25
  • 2020-08-26
  • 2012-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-19
相关资源
最近更新 更多