feat: 添加插入排序
This commit is contained in:
parent
e304e7378a
commit
eafe1e22fc
19
sort/insertion-sort.mjs
Normal file
19
sort/insertion-sort.mjs
Normal file
@ -0,0 +1,19 @@
|
|||||||
|
import { generateRandomArray, isSort } from "../util/index.mjs";
|
||||||
|
|
||||||
|
export function insertionSort(arr){
|
||||||
|
let n = arr.length;
|
||||||
|
for (let i = 1; i<n; i++) {
|
||||||
|
let currentElement = arr[i]
|
||||||
|
let j = i-1
|
||||||
|
while(j>=0 && arr[j] > currentElement) {
|
||||||
|
arr[j+1] = arr[j]
|
||||||
|
j--
|
||||||
|
}
|
||||||
|
arr[j+1] = currentElement
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let arr = generateRandomArray(1000)
|
||||||
|
|
||||||
|
insertionSort(arr)
|
||||||
|
console.log(isSort(arr));
|
Loading…
x
Reference in New Issue
Block a user