feat: 添加希尔序列的希尔排序

This commit is contained in:
LouisFonda 2024-02-24 14:45:34 +08:00
parent b72d56464e
commit aed06b9ad5

View File

@ -1,4 +1,21 @@
import { generateRandomArray, isSort } from "../util/index.mjs";
/*
希尔排序的性能与所选的间隔序列shell序列有关以下是几种常见的希尔排序序列
Hibbard 序列:
H(k) = 2^k - 1
1, 3, 7, 15, 31, ...
Sedgewick 序列:
H(k) = 9 * 4^k - 9 * 2^k + 1 4^k - 3 * 2^k + 1
1, 5, 19, 41, 109, ...
Knuth 序列:
H(k) = 3^k + 1
1, 4, 13, 40, 121, ...
这些序列在实际应用中可能产生不同的性能效果最佳序列可能取决于特定问题或数据集的性质
*/
/**
*
@ -31,3 +48,24 @@ export function shellSort(arr){
}
/**
* @description 使用希尔序列排序
* @param {number[]} arr
*/
export function shellSort2(arr) {
let n = arr.length
let gap = Math.floor(n / 2)
while (gap > 0) {
for(let i = 0;i<gap;i++) {
for(let j = i+gap;j<n;j+=gap){
const temp = arr[j]
while(j > 0 && arr[j-gap] > temp){ // 插入过程s
arr[j] = arr[j-gap]
j-=gap
}
arr[j] = temp
}
}
gap = Math.floor(gap / 2)
}
}