提问人:Linh Chi 提问时间:9/26/2023 更新时间:9/26/2023 访问量:47
在 JavaScript 中实现选择排序时出错
Error in implementing selection sort in JavaScript
问:
此代码用于在 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]));
答:
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; }
上一个:将鼠标悬停在树的整行上
下一个:Flutter 多个下拉问题
评论
cur
a[i]