zoukankan      html  css  js  c++  java
  • 归并排序


    public class 归并排序的实现
    {
        public static void main(String[] args)
        {
            int[] a =
            { 10, 32, 31, 56, 42, 38, 1, 85 };
            mergeSort(a, 0, a.length - 1);
            for (int i = 0; i < a.length; i++)
            {
                System.out.println(a[i]);
            }
        }

        /*
         * 定义:"归并"的含义是将二个或者两个以上的有序的表组合成一个有序的的表 假设两个有序表的长度分别为m和n 则可以在O(m+n)的时间量级上实现
         * 先分组然后合并
         */
        public static void mergeSort(int[] a, int begin, int end)
        {
            int mid = (begin + end) / 2;
            if (begin < end)
            {
                // 左边
                System.out.println("dfdf");
                mergeSort(a, begin, mid);
                // 右边
                mergeSort(a, mid + 1, end);
                // 合并
                mSort(a, begin, mid, end);
            }
        }

        private static void mSort(int[] a, int begin, int mid, int end)
        {
            int[] temp = new int[end - begin + 1];
            int i = begin, j = mid + 1, k = 0;
            while (i <= mid && j <= end)
            {
                if (a[i] < a[j])
                {
                    temp[k++] = a[i++];
                }
                else
                {
                    temp[k++] = a[j++];
                }
            }
            // 把左边的元素都移入数组当中
            while (i <= mid)
            {
                temp[k++] = a[i++];
            }
            // 把右边的元素都移入数组当中
            while (j <= end)
            {
                temp[k++] = a[j++];
            }
            // 覆盖原来的数组
            for (int k2 = 0; k2 < temp.length; k2++)
            {
                a[k2 + begin] = temp[k2];
            }
        }
    }

  • 相关阅读:
    EZOJ #202
    EZOJ #201
    p5156 [USACO18DEC]Sort It Out
    p4363 [九省联考2018]一双木棋chess
    p2150 [NOI2015]寿司晚宴
    p5155 [USACO18DEC]Balance Beam
    p2414 [NOI2011]阿狸的打字机
    实验室断网的解决方案
    人需要看到未来
    门德尔松--罗辑思维
  • 原文地址:https://www.cnblogs.com/qingtianBKY/p/7139155.html
Copyright © 2011-2022 走看看