博客
关于我
分治法之合并排序(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/

    你可能感兴趣的文章
    PHP获取IP的方法对比
    查看>>
    php获取json里面内容
    查看>>
    R2的版本由来
    查看>>
    PHP获取图片宽度高度、大小尺寸、图片类型、用于布局的img属性
    查看>>
    PHP获取当前文件的绝对路径
    查看>>
    PHP获取当前时间、时间戳的各种格式写法汇总
    查看>>
    PHP获取当前页面的完整URL
    查看>>
    php获取数据库中数据生成json,中文乱码问题的解决方案
    查看>>
    php获取文件夹中文件的两种方法
    查看>>
    PHP获取日期的一些方法总结
    查看>>
    R2学习记录
    查看>>
    PHP获取本周的每一天的时间
    查看>>
    php获取用户真实IP和防刷机制
    查看>>
    php获取网页内容的三种方法
    查看>>
    R-CNN算法优化策略
    查看>>
    PHP规范PSR0和PSR4的理解
    查看>>
    php解析ipa包,获取logo
    查看>>
    php设置cookie,在js中如何获取
    查看>>
    php设置socket超时时间
    查看>>
    php设计模式 萨莱 pdf,PHP设计模式 建造者模式
    查看>>