排序算法---归并排序

来源:互联网 发布:淘宝 笑涵阁 猫腻 编辑:程序博客网 时间:2024/05/21 15:29

归并排序

归并排序算法可以递归的描述为:算法将数组分为两半,对每部分递归的应用归并排序。在两部分都排好序后,对他们进行归并。
归并排序算法是递归+分治的最好体现之一。

算法的大致流程,如下图:

Java代码

使用Java代码实现归并特别简单,也很容易理解.

public class MergeSort {    public static void main(String[] args) {        int list[] = {2, 3, 2, 5, 6, 1, -2, 3, 14, 12};        mergeSort(list);        System.out.println(Arrays.toString(list));    } public static void mergeSort(int[] list) {        if (list.length > 1) {            //划分第一部分            int first[] = new int[list.length / 2];            System.arraycopy(list, 0, first, 0, list.length / 2);//复制            mergeSort(first);//递归            //划分第二部分            int second[] = new int[list.length - list.length / 2];            System.arraycopy(list, list.length / 2, second, 0, list.length - list.length / 2);//复制            mergeSort(second);//递归            int temp[] = merge(first, second);//归并的新数组            System.arraycopy(temp, 0, list, 0, temp.length);//复制        }    }    private static int[] merge(int[] first, int[] second) {        //归并的新数组        int temp[] = new int[first.length + second.length];        //分别记录first,second,temp的下标        int current1 = 0, current2 = 0, current3 = 0;        //在较短的数组长度内,将first与second升序合并到temp        while (current1 < first.length && current2 < second.length) {            if (first[current1] < second[current2]) {                temp[current3++] = first[current1++];            } else {                temp[current3++] = second[current2++];            }        }        //将较长部分剩余的添加到temp中        while (current1 < first.length) {            temp[current3++] = first[current1++];        }        while (current2 < second.length) {            temp[current3++] = second[current2++];        }        return temp;    }}

复杂度

归并排序是稳定的。O(nlogn).

原创粉丝点击