数据结构和算法算法和数据结构程序员

数据结构(十一):归并排序

2018-02-27  本文已影响71人  聪明的奇瑞

直接插入排序例子

直接插入排序代码

public static void main(String[] args) {
    int[] arr = new int[]{1, 3, 6, 4, 7, 8, 5, 10, 9};
    int[] temp = new int[arr.length];
    mergeSort(arr, temp, 0, arr.length - 1);
    System.out.println(Arrays.toString(temp));
}

public static void mergeSort(int[] a, int[] tmp, int left, int right) {
    if (left < right) {
        int mid = left + (right - left) / 2;
        mergeSort(a, tmp, left, mid);       // 左排序
        mergeSort(a, tmp, mid + 1, right);      // 右排序
        merge(a, tmp, left, mid + 1, right);        // 左右合并
    }
}

public static void merge(int[] a, int[] tmp, int left, int rightPos, int right) {
    int leftEnd = rightPos - 1;
    int tmpPos = left;
    int num = right - left + 1;
    while (left <= leftEnd && rightPos <= right) {
        if (a[left] < a[rightPos]) {
            tmp[tmpPos++] = a[left++];
        } else {
            tmp[tmpPos++] = a[rightPos++];
        }
    }
    while (left <= leftEnd) {
        tmp[tmpPos++] = a[left++];
    }
    while (rightPos <= right) {
        tmp[tmpPos++] = a[rightPos++];
    }
    for (int i = 0; i < num; i++, right--) {
        a[right] = tmp[right];
    }
}

归并排序性能

上一篇下一篇

猜你喜欢

热点阅读