归并排序
来源:互联网 发布:mac怎么输入emoji 编辑:程序博客网 时间:2024/04/28 04:33
1. 问题描述
2. 算法思想
利用分而治之和递归的思想将数据序列划分成越来越小的子表,再对子表排序,最后用递归的方法将排好序的子表合并为越来越大的有序序列。归并排序包括两个步骤:
1) 划分子表并排序
2) 合并子表
常见的为二路归并排序。
3. 伪代码实现
4. C++实现
const int MAXSIZE = 20;typedef struct RecordType{ KeyType key; InfoType otherinfo;}RecordType;typedef struct SqList{ RecordType r[MAXSIZE]; int length;}SqList;#include <cassert>#include <vector>/*Pre: "A" is an array. "A.r[p...q]" and "A.r[q+1...r]" are both sorted. q>=p and r>=q must hold.Post: merge the two sorted sub_array so that "A.r[p...r]" is sorted.*/void merge(SqList &A, int p, int q, int r){assert(q>=p && r>=q);const int n1 = q - p + 1;const int n2 = r - q;std::vector<RecordType> L(n1);std::vector<RecordType> R(n2);for (int i=0; i<n1; ++i)L[i] = A.r[p + i];for (int j=0; j<n2; ++j)R[j] = A.r[q + j + 1];int i = 0;int j = 0;for (int k=p; k<=r; ++k){if (i<L.size() && j<R.size()){if (L[i].key <= R[j].key)A.r[k] = L[i++];elseA.r[k] = R[j++];}else{if (i < L.size())A.r[k] = L[i++];if(j < R.size())A.r[k] = R[j++];}}}// 归并排序void merge_sort(SqList &L, int p, int r){assert(p <= r);if (p < r){int q = (p + r) / 2;merge_sort(L, p, q);merge_sort(L, q+1, r);merge(L, p, q, r);}}
4. 算法复杂度分析
时间复杂度:
空间复杂度为 。
稳定排序算法。
0 0
- 归并排序-归并排序
- 归并和归并排序
- 归并与归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 排序::归并
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- 归并排序
- nyoj 传纸条(一)
- 第7周作业1-循环大战
- Android多线程,让耗时的操作去后台,handler传递对象图片下载
- 32位与64位 CPU、编译器、操作系统与应用程序的区别
- MYSQL、SQL Server、Oracle数据库排序空值null问题及其解决办法
- 归并排序
- POJ 2752 Seek the Name, Seek the Fame
- curl 参数
- http请求的过程
- 阿七婆
- js
- Log4J的配置
- JSON(一种轻量级的数据交换格式)格式化工具
- mysql为数据库分配用户