博客
关于我
分治法之合并排序(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 字符串的几种拼装方式
    查看>>
    python 存入数据库bigint_python基础_MySQL的bigint类型
    查看>>
    python 学习 面向对象编程
    查看>>
    Python 学习日记第三篇 -- 字典
    查看>>
    Python 学习笔记(一)Data type
    查看>>
    python 安装echarts
    查看>>
    python 安装opencv及问题解决
    查看>>
    Python 安装程序:“写入文件 C:\Python27\pythonw.exe 时出错“
    查看>>
    Python 安装避坑指南:从入门到进阶
    查看>>
    Python 安装配置详解
    查看>>
    python 实现儿童算术游戏
    查看>>
    python 实现字符串转整型
    查看>>
    Python 实现定时任务的八种方案!
    查看>>
    Python 实现自动化测试 dubbo 协议接口
    查看>>
    python 对json数据读取及保存与读取,对dump,dumps,load,loads的理解
    查看>>
    Python 对mysql数据库的操作
    查看>>
    Python 对象数据库列表
    查看>>
    Python 导入requests报错No module named requests
    查看>>
    python 将函数加到列表中进行调用
    查看>>
    python 将图片与字符串相互转换
    查看>>