What is insertion sort
A very vivid example is given in the introduction to algorithm
Algorithm process
The following figure records a sorting process.
First, 2 and 5 are compared, 2 is smaller than 5, 2 and 5 are exchanged positions
4 and 5 are compared, 5 is greater than 4, and then compared with 2, and then inserted into the current position
...
Keep comparing until the compared number is greater than this number small
Algorithm implementation (javascript version)
The following algorithm is sorted from largest to smallest
function InsertionSort(arr) {
for (let j = 1; j < arr.length; j++) {
let key = arr[j];
let i = j - 1;
while (i >= 0 && arr[i] > key) {
arr[i + 1] = arr[i] //这里每次都交换
i = i - 1
}
arr[i + 1] = key
}
return arr
}