feat: 添加shell排序

This commit is contained in:
LouisFonda 2024-02-24 13:42:56 +08:00
parent 55a5055db3
commit b72d56464e

33
sort/shell-sort.mjs Normal file
View File

@ -0,0 +1,33 @@
import { generateRandomArray, isSort } from "../util/index.mjs";
/**
*
* @param {number[]} arr
*/
export function shellSort(arr){
const n = arr.length
// 创建希尔序列,以克努特序列为例
let gap = 1;
while (gap < n / 3) {
gap = gap*3 +1
}
while(gap>=1) {
// 正常插入排序
for (let i = 0;i<gap; i++){
for(let j = i+gap;j < n;j+=gap){
let temp = arr[j]
while(j>0 && arr[j-gap] > temp) {
arr[j] = arr[j-gap]
j-=gap
}
arr[j] = temp
}
}
// 正常插入排序
gap = Math.floor(gap/3)
}
}