关于原理,这里就不在多说了,我仅在这里贴上我撸的代码:
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 }
时间: 2024-10-05 23:09:06