博客
关于我
分治法之合并排序(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---使用celery分布式系统异步发送短信(云通讯)来验证登录
    查看>>
    python--003--百分号字符串拼接、format
    查看>>
    Python--10、线程
    查看>>
    Python--Redis实战:第四章:数据安全与性能保障:第4节:复制
    查看>>
    python--基本代码规范
    查看>>
    Python--抽象类接口类
    查看>>
    PYTHON--欧拉习题二
    查看>>
    python--高级应用总结
    查看>>
    python-520表白代码,我看谁说程序员不懂浪漫,送你几套表白代码,一步到位
    查看>>
    Python-Asyncio TypeError:无法在‘;等待‘;表达式中使用对象DICT
    查看>>
    Python-AttributeError:‘;dict&39;对象没有属性‘;序列‘;
    查看>>
    Python-ldap:是否可以在不显式写入密码的情况下进行绑定?
    查看>>
    python出现 unknown encoding: idna 的处理方法
    查看>>
    Python出现 RuntimeError: dictionary changed size during iteration 的解决方法
    查看>>
    Python-numpy(2)数组的操作
    查看>>
    Python-Numpy的tile函数用法
    查看>>
    python-open函数
    查看>>
    Python-Pandas-将特定函数应用于给定级别-多索引数据框架
    查看>>
    python-queue队列通信
    查看>>
    python-ros No module named PyKDL
    查看>>