使用扩展运算符 ( ...) 克隆原始数组arr。
使用for循环遍历数组中的元素。
使用Array.prototype.slice()和Array.prototype.reduce()查找子数组中当前索引右侧的最小元素的索引。如有必要,请执行交换。
JavaScript
const selectionSort = arr => {
const a = [...arr];
for (let i = 0; i < a.length; i++) {
const min = a
.slice(i + 1)
.reduce((acc, val, j) => (val < a[acc] ? j + i + 1 : acc), i);
if (min !== i) [a[i], a[min]] = [a[min], a[i]];
}
return a;
};
示例代码
selectionSort([5, 1, 4, 2, 3]); // [1, 2, 3, 4, 5]
更多内容请访问我的网站:https://www.icoderoad.com