發現菜鳥教程的那個圖片很明瞭的講述了
圖片來源:https://github.com/hustcc/JS-Sorting-Algorithm/blob/master/3.insertionSort.md
然後可以寫代碼了
function insert(arr){
var current;
for(let i=1;i<arr.length;i++){
current = arr[i];
preIndex = i-1;
while(preIndex >= 0 && arr[preIndex]>current){
arr[preIndex+1] = arr[preIndex];
preIndex--;
}
arr[preIndex+1] = current //這裏的preIndex要加1
}
return arr;
}
console.log(insert([1,2,3, 4,65,7,9,5]))