JAVA分治合并排序(MERGE-SORT)

/**
 * 分治算法.
 */
public class MergeSort {

    private MergeSort() {
        throw new RuntimeException();
    }

    public static void sort(int[] array) {
        if (null == array||array.length<2) {
            return;
        }
        sort(0, array.length, array);
    }

    private static void sort(int start, int length, int[] array) {
        if (length > 2) {
            int middle = (int) Math.floor(length / 2);
            sort(start, middle, array);
            sort(start + middle, length - middle, array);
            merge(start, middle, start + middle, length - middle, array);
        } else if (length == 2) {
            if (array[start+1]<array[start]){
                array[start+1] = array[start+1]^array[start];
                array[start] = array[start]^array[start+1];
                array[start+1] = array[start+1]^array[start];
            }
        }
    }

    private static void merge(int aStart, int aLength, int bStart, int bLength, int[] array) {
        int aSize = aStart + aLength;
        int bSize = bStart + bLength;
        while (aStart < aSize && bStart < bSize) {
            int a = array[aStart];
            int b = array[bStart];
            if (b<a){
                System.arraycopy(array, aStart, array, aStart + 1, bStart - aStart);
                array[aStart] = b;
                aStart++;
                bStart++;
                aSize++;
            }else {
                aStart++;
            }
        }
    }
}

推荐阅读更多精彩内容