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;
}
posted @ 2017-04-30 02:27  江湖一支竹  阅读(231)  评论(0编辑  收藏  举报