feat: 添加shell排序
This commit is contained in:
parent
55a5055db3
commit
b72d56464e
33
sort/shell-sort.mjs
Normal file
33
sort/shell-sort.mjs
Normal 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)
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
Loading…
x
Reference in New Issue
Block a user