排序算法之归并排序
2016-08-21 20:49
302 查看
<pre name="code" class="cpp">// MergeSort.cpp : Defines the entry point for the console application. // #include "stdafx.h" // SelectSort.cpp : Defines the entry point for the console application. // #include "iostream" using namespace std; // 归并排序:假设序列含义n 个记录,则可以看成是n 个长度均为1 的有序子序列(长度为1,当然有序), 然后两两归并,得到n/2 个长度为2 和 (n/2 - [n/2])个长度为1 的子序列([x]表示向上取整), // 继续两两归并,直到得到长度为n 的有序序列为止; // 将x[s..m], s[m+1,...t] 归并到 r[s...t] void Merge(double x[], double r[], int s, int m, int t) { // 将r[s..m] 和 r[m+1, ...,t] 归并为 a[s..t]; int i = 0; int j = 0; int k = s; for (i=s, j=m+1; i<=m && j<=t; NULL) { if (x[i] < x[j]) { r[k++] = x[i++]; } else { r[k++] = x[j++]; } } // 将剩余的拷贝, 下面两个for 循环,最终只执行一次; for (NULL; i<=m; NULL) { r[k++] = x[i++]; } for (NULL; j<=t; NULL) { r[k++] = x[j++]; } } void MergeSortSub(double a[], double r[], int s, int t, int n) { if (s == t) { r[s] = a[s]; } else { double *p = new double ; int m = (s + t) / 2; // a[s...m] 归并到有序子序列p[s...m]; MergeSortSub(a, p, s, m, n); // a[m+1...t] 归并到有序子序列p[m+1,...t]; MergeSortSub(a, p, m + 1, t, n); // 将p[s..m], s[m+1,...t] 归并到 r[s...t] Merge(p, r, s, m, t); delete[] p; p = NULL; } } void MergeSort(double a[], int n) { MergeSortSub(a, a, 0, n- 1, n); } int _tmain(int argc, _TCHAR* argv[]) { double a[] = {2.0, 5.4, 4.0, 8.0, 3.0, 5.0, 1.0, 9.0, 7.0}; int n = sizeof(a) / sizeof(*a); cout<<"排序前:\n"; for each (double x in a) { cout<<x<<" "; } cout<<endl; MergeSort(a, n); cout<<"排序后:\n"; for each (double x in a) { cout<<x<<" "; } cout<<endl; return 0; }
相关文章推荐
- 排序算法---归并排序
- 排序算法-归并排序
- 【排序算法】:归并排序
- 元素排序几种常用的排序算法的分析及java实现(希尔排序,堆排序,归并排序,快速排序,选择排序,插入排序,冒泡排序)
- 程序员必须掌握的8种排序算法(七):归并排序
- 排序算法(2)—归并排序,快速排序
- 漫谈经典排序算法:四、归并排序(合并排序)
- 归并排序(Merging Sort)----(排序算法十三)
- 排序算法(四)——归并排序与递归
- 用Python实现八大排序算法--归并排序
- 排序算法:归并排序
- 排序算法详解【归并排序-Merge_Sort】
- 数据结构之排序算法二:堆排序,快速排序,归并排序
- 排序算法之归并排序
- 排序算法 之 归并排序
- 排序算法1——归并排序
- Java(.NET)经典排序算法之归并排序
- 小学生图解排序算法:⑥归并排序
- 常见排序算法:归并排序
- 排序算法Java实现——归并排序