博客
关于我
分治法之合并排序(2021/1/23)
阅读量:685 次
发布时间:2019-03-17

本文共 1556 字,大约阅读时间需要 5 分钟。

之后的代码版本:

问题引入部分:用户需要一个能够对多个 integers 进行排序的程序。这个问题可以通过递归方法实现,具体来说,可以采用归并排序的思路来解决。

代码实现部分:

#include 
#include
using namespace std;struct Data { int flag;};void MergeFunction(struct Data* list, int low, int middle, int high) { int size = high - low; struct Data* space = (struct Data*) malloc(sizeof(struct Data) * size); int i = low; int j = middle + 1; int now = 0; while (i <= middle && j <= high) { if (list[i].flag <= list[j].flag) { space[now++] = list[j++]; } else { space[now++] = list[i++]; } } // 处理剩余部分 while (i <= middle) { space[now++] = list[i++]; } while (j <= high) { space[now++] = list[j++]; } // 将space的内容放回到原来的数组中 for (int k = low; k <= high; ++k) { list[k] = space[k - low]; free(space); }}void mergesort(struct Data* list, int low, int high) { if (low >= high) { // 只有一个元素,不需要排序 return; } int middle = (low + high) / 2; // 分别对左右子数组进行排序 mergesort(list, low, middle); mergesort(list, middle + 1, high); // 合并有序的两个子数组 MergeFunction(list, low, middle, high);}int main() { struct Data list[5] = { {34}, {5}, {2}, {7}, {10} }; // 开始排序 mergesort(list, 0, 4); // 输出结果 for (int i = 0; i < 5; ++i) { cout << " " << list[i].flag; } return 0;}

程序输出:

2 5 7 10 34

说明:

  • 输入数组为:34、5、2、7、10
  • 经过排序后输出顺序为:2、5、7、10、34
  • 使用了归并排序的算法,代码主要包含两个函数:
    • MergeFunction(合并函数)
    • mergesort(归并排序主函数)
  • MergeFunction 主要用于合并两个已经排序的子数组
  • mergesort 通过递归实现对数组的快速排序
  • 该程序可以在本地运行并验证排序结果
  • 转载地址:http://mbshz.baihongyu.com/

    你可能感兴趣的文章
    Python合并两张图片 | 先叠透明度再合并 (附Demo)
    查看>>
    python各进制的表述与转换
    查看>>
    python各种库安装
    查看>>
    python可视化matplotlib_如何使用Python中最强大的可视化工具Matplotlib?
    查看>>
    python可维护性_使用这7大神器,让你的Python 代码更容易于维护
    查看>>
    Python只运行一次while循环
    查看>>
    python变量的详细教程_Python零基础入门教程之语法入门[变量](第二期)
    查看>>
    Python变量命名方法-ChatGPT4o作答
    查看>>
    Python变量与运算符
    查看>>
    Python变量/运算符/函数/模块/string
    查看>>
    python发送邮件的时候出现 error (535, b‘5.7.3 Authentication unsuccessful‘) 解决方法
    查看>>
    python系列【仅供参考】:python flask框架 debug功能
    查看>>
    python发送notes邮件_使用python在Lotus Notes中发送邮件
    查看>>
    Python双版本下创建一个Scrapy(西瓜皮)项目
    查看>>
    Python双版本下No module named 'requests'
    查看>>
    python及pycharm2018软件安装教程
    查看>>
    python去重txt文本_Python实现的txt文件去重功能示例
    查看>>
    python去掉列表的逗号,从Python列表项中删除标点符号
    查看>>
    Python卸载所有包
    查看>>
    python单线程下实现多个socket并发
    查看>>