• 归并排序


    2——路归并排序,将序列两两分组进行排序,共有n/2组;然后再将这些组两两进行合并排序,得到n/4组,以此类推,直到只剩下一个组为止,此时这个组便是有序的。

    两两分组的时候,可以用基于二分的思想进行分组。

    void mergesort(int *a,int l,int r)
    {
        if(l>=r)
            return;
        else
        {
            int mid=l+(r-l)/2;
            mergesort(a,l,mid);
            mergesort(a,mid+1,r);
            my_merge(a,l,mid,mid+1,r);
        }
    }

    归并排序
    void my_merge(int *a,int l1,int r1,int l2,int r2)//两个有序序列,合并为一个有序序列,tow point :将两个有序序列合并为一个有序序列,O(n)

    void my_merge(int *a,int l1,int r1,int l2,int r2)//两个有序序列,合并为一个有序序列
    {
        int temp[r2-l1+1],index=0,i=l1,j=l2;
        while(i<=r1&&j<=r2)
        {
            if(a[i]<a[j])
                temp[index++]=a[i++];
            else
                temp[index++]=a[j++];
        }

        while(i<=r1)
            temp[index++]=a[i++];
        while(j<=r2)
            temp[index++]=a[j++];
        for(i=0;i<index;++i)
            a[l1+i]=temp[i];
    }

    1. /**
    2. 归并排序
    3. tow point :将两个有序序列合并为一个有序序列,O(n)
    4. */
    5. /**
    6. #include <iostream>
    7. #include <algorithm>
    8. #include <cmath>
    9. #include <cstdlib>
    10. using namespace std;
    11. void my_merge(int *a,int l1,int r1,int l2,int r2)//两个有序序列,合并为一个有序序列
    12. {
    13. int temp[r2-l1+1],index=0,i=l1,j=l2;
    14. while(i<=r1&&j<=r2)
    15. {
    16. if(a[i]<a[j])
    17. temp[index++]=a[i++];
    18. else
    19. temp[index++]=a[j++];
    20. }
    21. while(i<=r1)
    22. temp[index++]=a[i++];
    23. while(j<=r2)
    24. temp[index++]=a[j++];
    25. for(i=0;i<index;++i)
    26. a[l1+i]=temp[i];
    27. }
    28. void mergesort(int *a,int l,int r)
    29. {
    30. if(l>=r)
    31. return;
    32. else
    33. {
    34. int mid=l+(r-l)/2;
    35. mergesort(a,l,mid);
    36. mergesort(a,mid+1,r);
    37. my_merge(a,l,mid,mid+1,r);
    38. }
    39. }
    40. int main()
    41. {
    42. int n;
    43. cin >> n;
    44. int a[n];
    45. for(int i=0;i<n;++i)
    46. cin >> a[i];
    47. mergesort(a,0,n);
    48. for(auto b: a)
    49. cout << b << ' ';
    50. cout << endl;
    51. cout << "Hello world!" << endl;
    52. return 0;
    53. }

  • 相关阅读:
    数据结构每日亿题(二)
    数据库
    随手记录第一话 -- Java中的单点登录都有哪些实现方式?
    JVM学习第一天
    python 构建数组的方法
    MODBUS通信系列之数据处理
    前端悬浮菜单的实现方法及完整代码示例
    Java空指针异常的正确理解
    maven和gradle的比较与使用
    LeetCode每日一题(1300. Sum of Mutated Array Closest to Target)
  • 原文地址:https://blog.csdn.net/qq_51825761/article/details/125500142