合并排序 js版本

mergesort是合并排序。基本思路是将数列拆分为有序的子序列,再将子序列合并,完成排序。

// 合并排序函数
function mergesort(unsorted){
if(unsorted.length < 2){
    return unsorted;
}
else{
    var arr1=mergesort(unsorted.slice(0, unsorted.length/2));
    var arr2=mergesort(unsorted.slice(unsorted.length/2));
    var sorted = new Array();
    var i = 0;
    var j = 0;
    while(i < arr1.length || j < arr2.length)
    {
        if (i == arr1.length || (j != arr2.length && arr1[i] > arr2[j])) {
            sorted.push(arr2[j]);
            ++j;
        } else {
            sorted.push(arr1[i]);
            ++i;
        }
    }
    return sorted;
};

// 测试代码
var actual = mergesort([7,6,3,4,5,2,4,1]);
var ret = true;
var expect = [1,2,3,4,4,5,6,7];
for (var i = 0; i < expect.length; ++i) {
    if(actual[i] != expect[i]){
        ret = false;
        break;
}
document.body.innerHTML = ret ? "success":"failed";
点赞