Ideas
Take ascending order as an example:
- Find the smallest value in the array and place it in the first place of the array
- Find the second smallest value in the array and place it at the second place in the array
- By analogy, the execution
n-1
round can complete the sorting
The ascending order selection and sorting animation demonstration is shown in the figure:
Time complexity : O(n 2 )
achieve
Existing array [7, 5, 4, 15, 3, 9, 6, 12]
, sort in ascending order:
Array.prototype.selectionSort = function() {
// 重复(元素个数-1)次
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 = [7, 5, 4, 15, 3, 9, 6, 12];
arr.selectionSort();
console.log(arr);
Results of the: