从零开始学算法 - 插入排序

插入排序思路:
将数组分成array[0]~array[i-1]和array[i]~array[array.length-1]两部分。
前面排好序,后面乱序,取array[i]和排好序的部分从后向前依次比较,找到合适位置插入,直到排序完成。
 
用一个长度为10的数组,解释一下插入排序的过程:
原始数组:[72, 34, 51, 80, 14, 92, 84, 95, 68, 22]
将数组划分成两部分:[72],[34, 51, 80, 14, 92, 84, 95, 68, 22]
第一次遍历:
在左侧数组中插入34:[34, 72],[51, 80, 14, 92, 84, 95, 68, 22]
第二次遍历:
在左侧数组中插入51:[34, 51,  72],[80, 14, 92, 84, 95, 68, 22]
第三次遍历:
在左侧数组中插入80:[34, 51,  72, 80],[14, 92, 84, 95, 68, 22]
后续依次遍历插入,直到右侧数组没有数字。
 
将上述过程翻译成代码: 
function insertSort(arr){
  var preIndex,current;
  for(var i=1;i<arr.length;i++){
    preIndex
= i-1;     current = arr[i];     while(preIndex>=0 && arr[preIndex] > current){       arr[preIndex+1] = arr[preIndex];       preIndex--;     }   arr[preIndex+1] = current; }

 

posted @ 2018-10-24 23:46  月亮和电池  阅读(168)  评论(0编辑  收藏  举报