diff --git a/sort/select-sort.mjs b/sort/select-sort.mjs new file mode 100644 index 0000000..ccf3c63 --- /dev/null +++ b/sort/select-sort.mjs @@ -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); + +// 实际比较下来优化后的选择排序也没太大作用(实际开发不应使用这种排序,主要学习其解决思路) \ No newline at end of file