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

    归并排序主要就是先分解再合并的一个步骤:

    关于合并,以下是合并(合并里面是按大小顺序来合并,相当于排序)的实现代码:

    View Code
            void merge(int[] a, int head, int mid, int tail, int[] temp)
            {
                int i, j, k;
                i = head;
                j = mid+1;
                k = 0;
                while (i<=mid&&j<=tail)
                {
                    if (a[i] < a[j])
                        temp[k++] = a[i++];
                    else
                        temp[k++] = a[j++];
                }
                while (i<=mid)
                {
                    temp[k++] = a[i++];
                }
                while (j<=tail)
                {
                    temp[k++] = a[j++];
                }
                
                for ( i = 0; i < k; i++)
                {
                    a[head+i] = temp[i];
                }
            }

    以下是递归实现的代码:(主要就是递归实现分解,分解到不能再分解就开始合并)

    View Code
            static void sort(int[] a, int head, int tail, int[] temp)
            {
                if (head < tail)
                {
                    int mid = (head + tail) / 2;
                    sort(a, head, mid, temp);
                    sort(a, mid + 1, tail, temp);
                    merge(a, head, mid, tail, temp);
                }
     
            }

    关于这里面的一个递归,以下做一个图解,以便更好理解递归的意义:

    若待排数组为array[3]={3,1,7}

    主函数代码如下:

    View Code
           static void Main(string[] args)
            {
                int[] array ={ 3,1,7};
                int head = 0;
                int tail = array.Length - 1;
                int[] temp = new int[array.Length];
                for (int i = 0; i < array.Length; i++)
                {
                    temp[i] = array[i];
                }
                sort(array, head, tail, temp);
                for (int i = 0; i < array.Length; i++)
                {
                    Console.Write("{0}   ", array[i]);
                }
                
                Console.Read();
    
            }

    由代码可以看出,head=0,tail=2,mid=1
    则可以画出以下的递归层次图:

  • 相关阅读:
    hdu 6702 ^&^ 位运算
    hdu 6709 Fishing Master 贪心
    hdu 6704 K-th occurrence 二分 ST表 后缀数组 主席树
    hdu 1423 Greatest Common Increasing Subsequence 最长公共上升子序列 LCIS
    hdu 5909 Tree Cutting FWT
    luogu P1588 丢失的牛 宽搜
    luogu P1003 铺地毯
    luogu P1104 生日
    luogu P1094 纪念品分组
    luogu P1093 奖学金
  • 原文地址:https://www.cnblogs.com/huang1990/p/2999344.html
Copyright © 2011-2022 走看看