js實現插入排序

發現菜鳥教程的那個圖片很明瞭的講述了

 

圖片來源: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]))

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章