这个简单的mergeSort代码给出了错误的答案。有人能找到这个bug吗?

时间:2018-05-09 01:24:53

标签: javascript mergesort lexical

问题似乎是mergeSort将[300,200,100]分区为[300,200]和[100]。然后它成功合并并将[300,200]分类为[200,300]。现在出现问题:该算法不是将[200,300]与[100]合并,而是在[300]和[100]之间运行排序程序。我怀疑问题是因为Javascript的闭包,因此j的值在某些时候被解释得不同。有人能帮助我吗?

function mergeSort(A,start,end){
    console.log("Sorting " + A + " between " + start + " and " + end)
    if (start==end){
        console.log("Reached singleton element: " + A[start])
        return;
    } 

    j = Math.floor((end+start)/2);

    mergeSort(A,start,j);
    console.log("Sorted " + A + " between " + start + " and " + j + ". Now sorting between " + (j+1) + " and " + end)
    mergeSort(A,(j+1),end);
    merge(A,start,(j+1),end);
    return A
}  

function merge(A,s,p,e){ 
    var i = s;
    var j = p;
    var finalArray = [];
    while(i < p && j < e+1){
        if (A[i] <= A[j]){
            finalArray[i+j-s-p] = A[i];
            i++
        } 
        else if (A[j] < A[i]){
               finalArray[i+j-s-p] = A[j];
               j++
        }  
    }

    if (i == p){
        while (j < e+1 ){
            finalArray[i-s+j-p] = A[j];
            j++
        }
    }

    if (j == e+1){
        while (i < p ){
            finalArray[i-s +j-p] = A[i];
            i++ 
       }    
    }

    for(var q = s; q <e+1;q++){
        A[q] = finalArray[q-s]
    }
}



A = [300,200, 100] // Gives [ 200, 100, 300 ]
mergeSort(A, 0, (A.length-1));

1 个答案:

答案 0 :(得分:1)

这是一个范围问题。更改j的声明修复它:

let j = Math.floor((end+start)/2);

我重构了合并功能。我没有重命名变量的唯一原因是我在移动设备上。拥有更多js知识的人可能会有更多改进:

function merge(A,s,p,e) { 
    let i = s;
    let j = p;
    let finalArray = [];
    while(i < p && j <= e) {
        if (A[i] <= A[j]) {
            finalArray.push(A[i])
            i++
        } 
        else {
            finalArray.push(A[j])
            j++
        }  
    }

    while (j <= e) {
        finalArray.push(A[j]);
        j++
    }

    while (i < p) {
        finalArray.push(A[i]);
        i++  
    }

    for(let q = s; q <= e; q++) {
        A[q] = finalArray[q-s]
    }
}