首页 > 编程语言 > 详细

归并排序

时间:2020-08-02 23:55:01      阅读:138      评论:0      收藏:0      [点我收藏+]
import java.util.Arrays;

public class My {
    public void mergeSort(int[] arr, int low, int high) {
        if (low >= high) {
            return;
        }
        int mid = low / 2 + high / 2;
        mergeSort(arr, low, mid);
        mergeSort(arr, mid + 1, high);
        merge(arr, low, mid, high);
    }

    public void merge(int[] arr, int low, int mid, int high) {
        int n1 = mid - low + 1;
        int n2 = high - mid;
        int[] arr1 = new int[n1];
        int[] arr2 = new int[n2];
        for (int i = 0; i < n1; i++) {
            arr1[i] = arr[low + i];
        }
        //System.arraycopy(arr, low, arr1, 0, n1);
        for (int j = 0; j < n2; j++) {
            arr2[j] = arr[mid + 1 + j];
        }
        //System.arraycopy(arr, mid + 1, arr2, 0, n2);
        int i = 0, j = 0, k = low;
        while (i < n1 && j < n2) {
            if (arr1[i] <= arr2[j]) {
                arr[k] = arr1[i];
                k++;
                i++;
            } else {
                arr[k] = arr2[j];
                k++;
                j++;
            }
        }
        while (i < n1) {
            arr[k] = arr1[i];
            k++;
            i++;
        }
        while (j < n2) {
            arr[k] = arr2[j];
            k++;
            j++;
        }
    }

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

 

归并排序

原文:https://www.cnblogs.com/zzyf/p/13423711.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!