# 选择排序
解题思路:
- 遍历待排序列表, 查找到最小元素, 将最小的元素和列表第一项交换位置.
- 在剩余的元素中继续查找最小元素, 然后与列表第二项交换位置
- 依次类推, 直到排序完成
点击查看代码
/**
* 选择排序
* @param {number[]} arr
* @returns number[]
*/
const selectionSort = (arr) => {
if (arr.length <= 1) return arr
// console.time('--selection sort--')
for(let i = 0, len = arr.length; i < len - 1; i++) {
let minIndex = i
for(let j = i + 1; j < len; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j
}
}
if (minIndex !== i) {
// const temp = arr[i]
// arr[i] = arr[minIndex]
// arr[minIndex] = temp
[arr[i], arr[minIndex]] = [arr[minIndex], arr[i]]
}
}
// console.timeEnd('--selection sort--')
return arr
}
console.log(selectionSort([4, 8, 6, 2, 12, 0, 3]))
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28