js实现合并排序(归并排序)

let a = [3,4,1,2,5,6,2,3,1,7,9,8];

        // 合并排序(归并排序)

        function mergeSort(a,p,r){

            if(p

                let q = Math.floor((p+r)/2);

                mergeSort(a,p,q);

                mergeSort(a,q+1,r);

                merge(a,p,q,r);

            }

        }

        function merge(a,p,q,r){

            let L = a.slice(p,q+1);

            let R = a.slice(q+1,r+1);

            let i1 = 0;

            let i2 = 0;

            while(i1 != L.length && i2 != R.length){

                if(L[i1]<=R[i2]){

                    a[p] = L[i1];

                    i1 ++;

                    p ++;

                }else{

                    a[p] = R[i2];

                    i2 ++;

                    p ++;

                }

            }

            while(i1 != L.length){

                a[p] = L[i1];;

                i1 ++;

                p ++;

            }

            while(i2 != R.length){

                a[p] = R[i2];

                i2 ++;

                p ++;

            }

        }

        mergeSort(a,0,a.length-1);

        console.log(a);

你可能感兴趣的:(js实现合并排序(归并排序))