• 算法归并排序


    归并排序简言之,假设一个数组分成两个有同序的小数组(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快,我想我的快排写的有问题??? 我得研究一下了。

  • 相关阅读:
    科学使用睡眠周期,你会比别人拥有更多时间
    遇见那个对的人,便是爱情
    因为专注,所以伟大
    从来都没有爱情发生的人生
    每天只要做好三件事就行了 积跬步以至千里
    不读书的中国人
    两性思维的差异与情侣夫妻间争吵
    结婚的意义 — 几米
    二维码工具类
    验证码图片生成工具类——Captcha.java
  • 原文地址:https://www.cnblogs.com/ericwen/p/MergeSort.html
Copyright © 2020-2023  润新知