合并排序实现不适用于Javascript

时间:2016-02-26 07:14:11

标签: javascript algorithm sorting

我正在尝试了解有关排序算法的更多信息。这是我的合并排序实现。我的算法有什么问题吗?相信我错过了一些东西。



var arr = [1,5,3,2,4,78,3,2];

alert(mergeSort(arr));

function mergeSort(arr){
	var len = arr.length;
	var mid = Math.floor(len/2);
	var left = arr.slice(0,mid);
	var right = arr.slice(mid);

	if(len < 2) return arr;

	return merge(mergeSort(left),mergeSort(right));
}


function merge(left, right){
	var res = [];
	var lLeft = left.length;
	var lRight = right.length;
	var l = 0;
	var r = 0;

	while(l < lLeft && r < lRight){
		if(left[l] < right[r]){
			res.push(left[l++]);
		}else{
			res.push(right[r++]);	
		}
	}

	return res;
}
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

function mergeSort (arr) {    
    if (arr.length < 2) return arr;

    var mid = Math.floor(arr.length /2);
    var subLeft = mergeSort(arr.slice(0,mid));
    var subRight = mergeSort(arr.slice(mid));

    return merge(subLeft, subRight);
}

function merge (a,b) {
    var result = [];
    while (a.length >0 && b.length >0)
        result.push(a[0] < b[0]? a.shift() : b.shift());
    return result.concat(a.length? a : b);
}

var test = [1,5,3,2,4,78,3,2];
console.log(mergeSort(test));