algorighm/sort/insertion-sort.mjs

19 lines
351 B
JavaScript

/**
* 插入排序
* @param {number[]} arr
*/
function insertionSort(arr) {
const n = arr.length;
for (let i = 1; i < n; i++) {
const currentElement = arr[i];
let j = i - 1;
while (j >= 0 && arr[j] > currentElement) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = currentElement;
}
}
export default insertionSort;