javascript實現歸中算法

/**
* Created by kaer on 2017/4/29.
*/
//1.先將數組分爲兩部分,可用遞歸方式,最後數組只包含一個元素
//2.將各個單元素數據從新組合成排序後數組(捷徑:當數組只有兩個元素時,可直接排序,不須要進一步分解再組合)

function split(arr){
var len = arr.length;
if(len > 2)
{
var middle = Math.floor(len/2);
var preArr = arr.slice(0,middle);
var nextArr = arr.slice(middle,len);
return merge(split(preArr),split(nextArr));
}
var newArr = [];
if(len == 2)
{
if(arr[0] > arr[1])
{
newArr.push(arr[1]);
newArr.push(arr[0]);
return newArr;
}
return arr;
}
if(len ==1)
{
return arr;
}
}

function merge(aTmp,bTmp){
var a = aTmp;
var b = bTmp;
var newArr = [];
for(var i = 0;i<a.length;){
for(var j = 0;j< b.length;){
if(a[i] < b[j]){
newArr.push(a[i]);
a.splice(i,1);
continue;
}else{
newArr.push(b[j]);
b.splice(j,1);
}
}
break;
}
var alen = a.length;
var blen = b.length;
if(alen>0){
for(var i= 0;i<alen;i++){
newArr.push(a[i]);
}
}
if(blen > 0){
for(var i= 0;i<blen;i++){
newArr.push(b[i]);
}
}
return newArr;
}

console.log(split([5,2,6,3,4,0,1]));



改進:
function merge(aTmp,bTmp){    var a = aTmp;    var b = bTmp;    var newArr = [];    var len = a.length + b.length;    var alen = a.length;    var blen = b.length;    console.log(len);    console.log(a);    console.log(b);    for(var i=0,j=0,k=0;k<len;k++){        if(a[i] < b[j]){            if(i<alen){                newArr.push(a[i]);                i++;            }            else{                newArr.push(b[j]);                j++;            }        }else{            if(j<blen){                newArr.push(b[j]);                j++;            }            else{                newArr.push(a[i]);                i++;            }        }    }    /*    for(var i = 0;i<a.length;){        for(var j = 0;j< b.length;){            if(a[i] < b[j]){                newArr.push(a[i]);                a.splice(i,1);                continue;            }else{                newArr.push(b[j]);                b.splice(j,1);            }        }        break;    }    var alen = a.length;    var blen = b.length;    if(alen>0){        for(var i= 0;i<alen;i++){            newArr.push(a[i]);        }    }    if(blen > 0){        for(var i= 0;i<blen;i++){            newArr.push(b[i]);        }    }*/    return newArr;}
相關文章
相關標籤/搜索