归并排序

相当高效的稳定排序算法,但空间复杂度较大。

典型的分治思想。而将两个有序的数组合并起来也很简单,只需另开一个数组再不断取它们的较小值即可。

public static void mergeSort(int[] A){
    mergeSortDo(A, 0, A.length-1);
}

private static void mergeSortDo(int[] A, int low, int high){
    if(low < high){
        int mid = (low + high) / 2;
        mergeSortDo(A, low, mid);
        mergeSortDo(A, mid+1, high);
        merge(A, low, mid, high);
    }    
}

private static void merge(int[] A, int low, int mid, int high){
    int i = low, j = mid + 1, k = 0;
    int[] tmp = new int[high - low + 1];
    while(i <= mid && j <= high){
        if(A[i] < A[j]){
            tmp[k ++] = A[i ++];
        }
        else{
            tmp[k ++] = A[j ++];
        }
    }
    while(i <= mid){
        tmp[k ++] = A[i ++];
    }
    while(j <= high){
        tmp[k ++] = A[j ++];
    }
    System.arraycopy(tmp, 0, A, low, tmp.length);
}
Java

 

posted @ 2013-10-21 20:37  7hat  阅读(184)  评论(0编辑  收藏  举报