排序算法的java实现-归并排序

来源:互联网 发布:java调用com组件 编辑:程序博客网 时间:2024/05/16 15:29
原始数组:49, 38, 65, 97, 76, 13, 27,49分组:[49, 38, 65, 97] [76, 13, 27,49]继续分组:[49,38] [65,97] [76,13] [27,49]
第一次合并:[38,49] [65,97] [13,76] [27,49]
第二次合并:[38,49,65,97] [13,27, 49, 76]
第三次合并:[13, 27, 38, 49, 49, 65, 76, 97]
import java.util.Arrays;/** * @author zhuangguoshuai * @description * @create 2017-10-18 17:13 **/public class MergeSort {    public static void partition(int[] array, int from, int to)    {        if(from < to) {            int mid = (from + to) / 2;            partition(array, from, mid);            partition(array, mid+1, to);            merge(array, from, mid, to);        }    }    public static void merge(int[] array, int from, int mid ,int to) {        int[] c = new int[to - from + 1] ;        int ai = from;        int bi = mid + 1;        int ci = 0;        while(ai <= mid && bi <= to)  {            if(array[ai] <= array[bi]) {                c[ci++] = array[ai++];            }            else {                c[ci++] = array[bi++];            }        }        while(bi <= to){            c[ci++] = array[bi++];        }        while(ai <= mid) {            c[ci++] = array[ai++];        }        System.arraycopy(c, 0, array, from, c.length);    }    public static void main(String[] args) {        int[] array = new int[]{49, 38, 65, 97, 76, 13, 27,49};        partition(array,0, array.length-1);        System.out.println(Arrays.toString(array));    }}
性能分析:
最坏=平均=O(N*lgN) 额外空间:O(N)
原创粉丝点击