feat: 添加选择排序

This commit is contained in:
LouisFonda 2024-02-22 23:04:21 +08:00
parent 167bb9f481
commit e304e7378a

69
sort/select-sort.mjs Normal file
View File

@ -0,0 +1,69 @@
import { generateRandomArray, isSort, swap } from "../util/index.mjs"
/**
*
* @param {number[]} arr
* @description 朴素的冒泡排序
*/
export function selectSort(arr) {
let len = arr.length
for(let i = 0; i< len; i++) {
let minIndex = i
for(let j = i+1; j < len; j++) { // 找到本轮最小的值
if(arr[j] < arr[minIndex]) {
minIndex = j
}
}
swap(arr, i, minIndex); // 交换最小值和选择值的下标
}
}
/**
*
* @param {number[]} arr
* @description 两端同时排序类似鸡尾酒排序
*/
function selectSort2(arr) {
let left = 0;
let right = arr.length - 1;
while (left < right) {
let minIndex = left;
let maxIndex = right;
for (let i = left; i <= right; i++) {
// 寻找最小值的索引
if (arr[i] < arr[minIndex]) {
minIndex = i;
}
// 寻找最大值的索引
if (arr[i] > arr[maxIndex]) {
maxIndex = i;
}
}
// 将最小值交换到左边
[arr[left], arr[minIndex]] = [arr[minIndex], arr[left]];
// 如果最大值的索引是左边的索引,由于上一步交换,所以更新为最小值的索引
if (maxIndex === left) {
maxIndex = minIndex;
}
// 将最大值交换到右边
[arr[right], arr[maxIndex]] = [arr[maxIndex], arr[right]];
// 更新左右指针
left++;
right--;
}
}
let arr = generateRandomArray(10)
console.log(arr);
selectSort2(arr)
console.log(isSort(arr));
console.log(arr);
// 实际比较下来优化后的选择排序也没太大作用(实际开发不应使用这种排序,主要学习其解决思路)