选择排序(ts实现)
# 算法步骤
首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置。
再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。
重复第二步,直到所有元素均排序完毕。
# Code:
/**
@Project :算法
@File : index1
@IDE : WebStorm
@Author : xinyu
@Date :2022/3/2 下午4:33
@Description :选择排序
**/
import baseFunction = require("../utils/baseUtils");
let baseFunctions = new baseFunction()
let selectionSort = (array, compareFn = baseFunctions.defaultCompare) => {
const {length} = array;
let indexMin;
for (let i = 0; i < length - 1; i++) {
indexMin = i;
for (let j = i; j < length; j++) {
if (compareFn.call(baseFunctions, array[indexMin], array[j]) === baseFunctions.Compare.BIGGER_THAN)
indexMin = j;
}
if (i !== indexMin)
baseFunctions.swap(array, i, indexMin)
}
return array
}
console.log(selectionSort(baseFunctions.testArray));
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
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
上次更新: 2023/09/05 17:45:42