// 选择排序法,每次遍历一遍数组,找到最小的,与其进行交换
// 复杂度O(n方)
let arr = [5, 1, 8, 3, 4, 2, 6, 7];
function select_sort(arr) {
for (let index = 0; index < arr.length; index++) {
let item1 = arr[index];
let min_index = index;
for (let area_index = index; area_index < arr.length; area_index++) {
let itme2 = arr[area_index];
if (itme2 < item1) {
min_index = area_index;
item1 = itme2;
}
}
let temp = arr[index];
arr[index] = arr[min_index];
arr[min_index] = temp;
}
}
select_sort(arr);
console.log(arr);
运行结果
[ 1, 2, 3, 4,5, 6, 7, 8]