选择排序
2020-3-22
BY zhouzh1
/**
* 选择排序,时间复杂度为O(N^2)
*/
function selectSort(arr) {
for (let i = 0; i < arr.length - 1; i++) {
let idxOfMinVal = i, curVal = arr[i];
for (let j = i + 1; j < arr.length; j++) {
if (arr[j] < curVal) {
curVal = arr[j];
idxOfMinVal = j;
}
}
if (idxOfMinVal != i) {
[arr[i], arr[idxOfMinVal]] = [arr[idxOfMinVal], arr[i]];
}
}
}
// test
const arr = new Array(10);
for (let i = 0; i < arr.length; i++) {
arr[i] = Math.round(Math.random() * 90 + 10)
}
console.log(arr);
selectSort(arr);
console.log(arr);