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

    归并排序简言之,假设一个数组分成两个有同序的小数组(1/2组),然后将二者合并。

    递归的假设,将小组再假设分成两个有同序的小组(1/4组),然后合并二者。

    递归。。。。

    最后1/n组剩下一个数据了,两个1/n组合并。这应该easy哈。

    递归实现如下:

            /// <summary>
            
    /// Merge Sort O(nlogn)
            
    /// </summary>
            
    /// <param name="arr"></param>
            public static void MergeSort(int[] arr)
            {
                if (arr == null)
                {
                    throw new ArgumentNullException();
                }

                MergeSort(arr, 0, arr.Length - 1);
            }

            private static void MergeSort(int[] arr, int first, int last)
            {
                if (arr == null)
                {
                    throw new ArgumentNullException();
                }

                if (first < last)
                {
                    int mid = (first + last) / 2;
                    // Split the original array to two small arrays,[first,mid] and [mid+1,last]
                    MergeSort(arr, first, mid);
                    MergeSort(arr, mid + 1, last);

                    // Merge two small arrays to an array
                    int index1 = first;
                    int index2 = mid + 1;
                    int[] tempArr = new int[last - first + 1];
                    int tempIndex = 0;
                    while (index1 <= mid && index2 <= last)
                    {
                        if (arr[index1] < arr[index2])
                        {
                            tempArr[tempIndex++] = arr[index1];
                            index1++;
                        }
                        else
                        {
                            tempArr[tempIndex++] = arr[index2];
                            index2++;
                        }
                    }

                    while (index1 <= mid)
                    {
                        tempArr[tempIndex++] = arr[index1];
                        index1++;
                    }

                    while (index2 <= last)
                    {
                        tempArr[tempIndex++] = arr[index2];
                        index2++;
                    }

                    tempIndex = 0;
                    while (tempIndex < tempArr.Length)
                    {
                        arr[first + tempIndex] = tempArr[tempIndex];
                        tempIndex++;
                    }
                }
            }

    我发现这个归并也我写QuickSort快,我想我的快排写的有问题??? 我得研究一下了。

  • 相关阅读:
    redmine工作流程总结
    IOS_OC_Category
    权限问题导致无法删除ftp文件
    Window下UDP(socket)接和收数据案例
    新一批创业者入局 谁来挖掘其身上的金矿
    java代理使用 apache ant实现文件压缩/解压缩
    ZOJ Monthly, November 2012
    【cocos2d-x 3.7 飞机大战】 决战南海I (十) 游戏主场景
    getAttribute for IE7
    Sahara中的数据模型
  • 原文地址:https://www.cnblogs.com/ericwen/p/MergeSort.html
Copyright © 2011-2022 走看看