归并排序

2018-07-27 21:04 更新
  1. 基本思想: 归并(Merge)排序法是将两个(或两个以上)有序表合并成一个新的有序表,即把待排序序列分为若干个子序列,每个子序列是有序的。然后再把有序子序列合并为整体有序序列。
  2. 代码实现:
    
    /**
     * 打印数组内容
     * 
     * @param a
     */
    public static void saymsg(int[] src) {
        for (int i = 0; i < src.length; i++) {
            System.out.print(src[i]);
            System.out.print(",");
        }
        System.out.println();
    }

public static void mergingSort(int[] data, int left, int right) { if (left < right) { // System.out.println(left+";"+right); int center = (left + right) / 2; mergingSort(data, left, center); mergingSort(data, center + 1, right); merge(data, left, center, right);

} }

public static void merge(int[] data, int left, int center, int right) { // System.out.println(left+";"+center+";"+right); int[] tmpArr = new int[data.length]; int mid = center + 1; int third = left; int tmp = left; while (left <= center && mid <= right) { if (data[left] <= data[mid]) { tmpArr[third++] = data[left++]; } else { tmpArr[third++] = data[mid++]; } } while (mid <= right) { tmpArr[third++] = data[mid++]; } while (left <= center) { tmpArr[third++] = data[left++]; } while (tmp <= right) { data[tmp] = tmpArr[tmp++]; } saymsg(data); }

public static void main(String[] args) { int[] src = { 49, 38, 65, 97, 76, 13, 27, 49, 78, 34, 12, 64, 5, 4, 62, 99, 98, 54, 56, 17, 18, 23, 34, 15, 35, 25, 53, 51 }; System.out.println("原始数组排序:"); saymsg(src); if (src.length > 0) { mergingSort(src, 0, src.length - 1); } }


两个方法可以分开理解,第一个 是一个待比较排序组合,第二个是数值的比较


![](//atts.w3cschool.cn/attachments/image/20170727/1501127342130116.gif)
*图片来自维基百科*
以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号