归并排序

归并排序

package org.study.order;


import java.util.Arrays;

public class MergeSort02 {

    public static void merge(int[] arr, int left, int mid, int right) {
        int[] tmp = new int[arr.length]; //先创建一个临时的数组,用于存放排序的元素

        int p1 = left, p2 = mid + 1, k = left;

        while (p1 <= mid && p2 <= right) {
            if (arr[p1] <= arr[p2]) {
                tmp[k] = arr[p1];
                k ++;
                p1 ++;
            } else {
                tmp[k] = arr[p2];
                k ++;
                p2 ++;
            }
        }

        while (p1 <= mid) {
            tmp[k] = arr[p1];
            k ++;
            p1 ++;
        }

        while (p2 <= right) {
            tmp[k] = arr[p2];
            k ++;
            p2 ++;
        }

        for (int i = left; i <= right; i ++) {
            arr[i] = tmp[i];
        }

    }

    public static void mergeSort(int[] arr, int left, int right) {

        if (left >= right) return;
        int mid = (left + right) >> 1;
        mergeSort(arr, left, mid);
        mergeSort(arr, mid + 1, right);
        merge(arr, left, mid, right);
    }


    public static void main(String[] args) {
        int[] arr = { 49, 38, 65, 97, 76, 13, 27, 50 };
        mergeSort(arr, 0, arr.length - 1);
        System.out.println(Arrays.toString(arr));
    }
}

posted @ 2021-03-06 22:57  Leo-Wong  阅读(19)  评论(0编辑  收藏  举报