signed

QiShunwang

“诚信为本、客户至上”

归并排序—Java

2021/4/26 21:14:28   来源:
public  int[] MergeSort(int[] sortarray){
        if (sortarray.length<2) return sortarray;
        int mid=sortarray.length/2;//将序列拆分为两个子序列
        int[] left= Arrays.copyOfRange(sortarray,0,mid);
        int[] right=Arrays.copyOfRange(sortarray,mid,sortarray.length);
        return merge(MergeSort(left),MergeSort(right));//递归使用归并排序
    }

public  int[] merge(int[] left, int[] right) {//两个归并排序拆分的两个子序列合并为一个序列
        int[] res=new int[left.length+right.length];
        for (int index = 0,i=0,j=0; index <res.length ; index++) {
            if (i>=left.length){
                res[index]=right[j++];
            }
            else if (j>=right.length){
                res[index]=left[i++];
            }
            else if (left[i]<right[j]){
                res[index]=left[i++];
            }
            else {
                res[index]=right[j++];
            }
        }
        return  res;
    }