首页 > 编程语言 > 详细

归并排序

时间:2016-02-16 16:37:21      阅读:165      评论:0      收藏:0      [点我收藏+]
/**
     * 归并排序
     * 进行左右排序,然后归并,
     * @param numbers
     * @param low
     * @param high
     */
    static void mergeSort(int[] numbers,int low,int high){
        int mid = (high + low)/2;
        if (low < high) {
            //左排序
            mergeSort(numbers, low, mid);
            //右排序
            mergeSort(numbers, mid + 1 , high);
            //归并
            merge(numbers, low, mid, high);
        }
        
    }
static void merge(int[] numbers,int low,int mid,int high){
        int[] tmp = new int[high - low + 1];
        int i = low;//左指针
        int j = mid + 1;//右指针
        int k = 0;
        while(i <= mid&&j <= high){
            if (numbers[i] < numbers[j]) {
                tmp[k++] = numbers[i++]; 
            }else {
                tmp[k++] = numbers[j++];
            }
        }
        while (i <= mid) {
            tmp[k++] = numbers[i++];
        }
        while (j <= high) {
            tmp[k++] = numbers[j++];
        }
        
        for (int k2 = 0; k2 < tmp.length; k2++) {
            numbers[k2 + low] = tmp[k2];
        }
    }

 

归并排序

原文:http://www.cnblogs.com/phyxis/p/5192918.html

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