我应该如何在递归函数中使用函数setInterval(),比如mergeSort?

时间:2016-04-10 04:26:19

标签: javascript setinterval

MergerSort函数作为递归函数,我想在调用merge_sort_auto时显示每一步,但它没有按预期工作!

function merge_sort_auto(arr,start,end){
        showArray(arr);//I want to show my array here!
        if (start < end) {
            setTimeout(function() {     //can setInterval work here? 
            var mid = Math.floor((start + end) / 2);
            merge_sort_auto(arr, start, mid);//first part
            merge_sort_auto(arr, mid + 1, end);//second part
            //merge here
            var ARR = new Array(end - start + 1);
            var k = 0, k1 = 0, k2 = 0;
            while (k1 != mid - start + 1 && k2 != end - mid) {
                if (arr[start + k1] < arr[mid + 1 + k2]) {
                    ARR[k++] = arr[start + k1++];
                } else {
                    ARR[k++] = arr[mid + 1 + k2++];
                }
            }
            if (k1 == mid - start + 1) {
                while (k2 < end - mid) {
                    ARR[k++] = arr[mid + 1 + k2++];
                }
            }
            if (k2 == end - mid) {
                while (k1 < mid - start + 1) {
                    ARR[k++] = arr[start + k1++];
                }
            }
            k = 0;
            for (var x = start; x <= end; x++) {
                arr[x] = ARR[k++];
            }
            },100);
        }
}

它没有按预期工作,为什么呢?谢谢!

0 个答案:

没有答案