# 选择排序
# 选择排序的思路
找到数组中的最小值,选中它并将它放置在第一位。
接着找到第二小的值,选中它并将它放置在第二位。
# JS实现
Array.prototype.selectionSort = function () {
for (let i = 0; i < this.length - 1; i++) {
let indexMin = i;
for (let j = i; j < this.length; j++) {
if (this[j] < this[indexMin]) {
indexMin = j;
}
}
if(indexMin !== i){
let temp = this[i];
this[i] = this[indexMin];
this[indexMin] = temp;
}
}
}
const arr = [5, 4, 3, 2, 1];
arr.selectionSort()
console.log(arr)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# 选择排序的时间复杂度
两个嵌套循环
时间复杂度 O(n^2)