在 JavaScript 中实现选择排序时出错

Error in implementing selection sort in JavaScript

提问人:Linh Chi 提问时间:9/26/2023 更新时间:9/26/2023 访问量:47

问:

此代码用于在 JavaScript 中实现选择排序。我尝试使用数组 [3,2,1],但它返回 [1,1,1];数组 [4,5,1,2,7] 返回 [1,1,1,2,7]。我不知道我哪里做错了。请帮忙!

function selectionSort(a) {
  var temp;
  for (let i = 0; i < a.length - 1; i++) {
    cur = a[i];
    for (let j = i + 1; j < a.length; j++) {
      if (a[j] < cur) {
        cur = a[j];
      }
    }
    if (a[i] != cur) {
      temp = cur;
      cur = a[i];
      a[i] = temp;
    }
  }
  return a;
}
console.log(selectionSort([4,5,1,2,7]));
JavaScript 排序 for 循环 逻辑 选择

评论

0赞 Barmar 9/26/2023
您需要记住来自哪里的索引。然后,您应该将该索引替换为 。cura[i]

答:

1赞 Dhruv Patel 9/26/2023 #1

选择排序实现中的问题在于,当您在内部循环中找到较小的元素时,您没有正确交换值。要解决此问题,您需要通过将当前最小值存储在临时变量中,然后将其分配到数组中的正确位置来交换元素。

function selectionSort(a) {
  for (let i = 0; i < a.length - 1; i++) {
    let minIndex = i; // Assume the current index contains the minimum value

    for (let j = i + 1; j < a.length; j++) {
      if (a[j] < a[minIndex]) {
        minIndex = j; // Update the index of the minimum value
      }
    }

    // Swap the elements at minIndex and i
    if (minIndex !== i) {
      let temp = a[i];
      a[i] = a[minIndex];
      a[minIndex] = temp;
    }
  }

  return a;
}

console.log(selectionSort([4, 5, 1, 2, 7]));
-1赞 bhavna parmar 9/26/2023 #2

使用 sort 函数对数组进行排序 function selectionSort(array) { array.sort( function(a,b) { return a-b } ); return array; }

评论

0赞 Community 9/27/2023
您的答案可以通过额外的支持信息得到改进。请编辑以添加更多详细信息,例如引文或文档,以便其他人可以确认您的答案是正确的。您可以在帮助中心找到有关如何写出好答案的更多信息。