排序算法系列之归并算法

Posted 我是畅游海

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了排序算法系列之归并算法相关的知识,希望对你有一定的参考价值。

关于原理,这里就不在多说了,我仅在这里贴上我撸的代码:

 1 #include<iostream>
 2 using namespace std;
 3 
 4 const int N = 9;
 5 static int c = 0;
 6 
 7 void Merge(int sr[], int tr[], int s, int m, int t){
 8     int i=s, j=m+1, k=0;
 9     for (; s <= m &&j <= t; i++){
10         if (sr[s] < sr[j]){
11             tr[i] = sr[s++];
12         }
13         else{
14             tr[i] = sr[j++];
15             ++c;
16         }
17     }
18     if (s <= m){
19         for (k = 0; k <= m - s; k++){
20             tr[i + k] = sr[s + k];
21             ++c;
22         }
23     }
24     if (j <= t){
25         for (k = 0; k <= t - j; k++){
26             tr[i + k] = sr[j + k];
27         }
28     }
29 }
30 
31 
32 void MSort(int sr[], int tr1[], int s, int t){
33     int tr2[N];
34     int mid;
35     if (s == t){
36         tr1[s] = sr[s];
37     }
38     else{
39         mid = (s + t) / 2;
40         MSort(sr, tr2, s, mid);
41         MSort(sr, tr2, mid + 1, t);
42         Merge(tr2, tr1, s, mid, t);
43     }
44 }
45 
46 void MergSort(int a[], int n)
47 {
48     int b[9];
49     MSort(a, b, 0, 8);
50 }
51 
52 int main(){
53     int a[] = { 9, 5, 1, 6, 2, 3, 8, 4, 7 };
54     int n = 9;
55     MergSort(a,n);
56     return 0;
57 }

 

以上是关于排序算法系列之归并算法的主要内容,如果未能解决你的问题,请参考以下文章

基础算法系列之排序算法[快速排序,归并排序,二分查找]

JavaScript算法 ,Python算法,Go算法,java算法,系列之归并排序篇

JavaScript算法 ,Python算法,Go算法,java算法,系列之归并排序篇

白话经典算法系列之五 归并排序的实现

C++ 不知算法系列之聊聊希尔归并排序算法中的分治哲学

白话经典算法系列之五 归并排序的实现