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];
            }
        }
    }

  • 相关阅读:
    POJ 2299 UltraQuickSort(求逆序数,归并排序或者离散化+树状数组)
    HDU 4349 Xiao Ming's Hope(数学题)
    HDU 2222 Keywords Search(AC自动机的入门题)
    HDU 4341 Gold miner(分组的背包问题)
    HDU 2825 Wireless Password(AC自动机+状态压缩DP)
    POJ 2352 Stars(树状数组)
    HDU 4342 History repeat itself(数学规律)
    HDU 4345 Permutation(数学题,记忆化搜索)
    HDU 3247 Resource Archiver(AC自动机+状态压缩DP)
    RFC
  • 原文地址:https://www.cnblogs.com/qingtianBKY/p/7139155.html
Copyright © 2011-2022 走看看