javascript實現插入排序(直接插入排序和希爾排序)

/** * Created by kaer on 2017/4/30. *///直接插入排序:取數組第一個做爲基準值,其它值以它爲基準順序插入function straight (a){    var newArr = [];    var first = a[0];    var len = a.length;    newArr.push(first);    for(var i = 1;i<len;i++){        var newLen = newArr.length;        var b = true;        for(var j = 0;j<newLen;j++){            if(newArr[j]>a[i]){                newArr.splice(j,0,a[i]);                b = false;                break;            }        }        if(b){            newArr.push(a[i]);        }    }    return newArr;}//console.log(straight([5,2,6,3,4,1,0]));//希爾排序:直接插入排序的改進版,以len/2,len/4,len/8....1,爲間隔從原數組中取值,分別應用直接排序function shellSort(a){    var len  = a.length;    for(var n=Math.floor(len/2);n>=1;n=Math.floor(n/2)){        for(var i=0;(i+n)<len;i++){            var arrTmp = [];            var iTmp = [];            var sortArr = [];            for(var k=i,j=0;k<len;j++,k=i+j*n){                arrTmp.push(a[k]);              //  console.log(arrTmp);                iTmp.push(k);            }            sortArr = straight(arrTmp);            for(var m =0;m<sortArr.length;m++){                a[iTmp[m]] = sortArr[m];            }        }    }    console.log(a);}shellSort([5,2,6,3,4,1,0]);
相關文章
相關標籤/搜索