两个有序数组合并为一个及归并排序实例

import com.alibaba.fastjson.JSON;

public class MergeSort {

    //将有序数组a[]和b[]合并到c[]中
    void MemeryArray(int[] a, int n, int[] b, int m, int[] c)
    {
        int i, j, k;

        i = j = k = 0;
        while (i < n && j < m)
        {
            if (a[i] < b[j])
                c[k++] = a[i++];
            else
                c[k++] = b[j++];
        }

        while (i < n)
            c[k++] = a[i++];

        while (j < m)
            c[k++] = b[j++];
    }

    void mergearray(int[] a, int first, int mid, int last, int[] temp)
    {
        int i = first, j = mid + 1;
        int m = mid,   n = last;
        int k = 0;

        while (i <= m && j <= n)
        {
            if (a[i] <= a[j])
                temp[k++] = a[i++];
            else
                temp[k++] = a[j++];
        }

        while (i <= m)
            temp[k++] = a[i++];

        while (j <= n)
            temp[k++] = a[j++];

        for (i = 0; i < k; i++)
            a[first + i] = temp[i];
    }

    void mergesort(int[] a, int first, int last, int[] temp)
    {
        if (first < last)
        {
            int mid = (first + last) / 2;
            mergesort(a, first, mid, temp);    //左边有序
            mergesort(a, mid + 1, last, temp); //右边有序
            mergearray(a, first, mid, last, temp); //再将二个有序数列合并
        }
    }

    boolean MergeSort(int[] a, int n)
    {
        int[] p = new int[n];
        if (p == null)
            return false;
        mergesort(a, 0, n - 1, p);
        return true;
    }


    public static void main(String[] args) {
        MergeSort mergeSort = new MergeSort();
        int[] a = {1,3,5,7,9,11,12,13};
        int[] b = {2,3,6,8,10};

        int[] c = new int[a.length + b.length];

        mergeSort.MemeryArray(a, a.length, b, b.length, c);

        System.out.println(JSON.toJSONString(c));

        int[] arr = {11, 3, 1, 4, 1, 2, 20, 5, 10, 6};

        mergeSort.MergeSort(arr, arr.length);

        System.out.println(JSON.toJSONString(arr));
    }
}

阿莫斯论Amos

posted @ 2017-04-05 17:29  Andrew.Zhou  阅读(4732)  评论(0编辑  收藏  举报