1 #include<iostream> 2 using namespace std; 3 4 #define N 100 5 6 int g_array[N]; //存放输入的数字 7 static int count; //存放元素的个数 8 9 //初始化函数 10 void Initial() 11 { 12 cout << "请输入元素的个数:"; 13 cin >> count; 14 cout << "请输入" << count << "个元素:"; 15 for(int i = 0; i < count; i++) 16 { 17 cin >> g_array[i]; 18 } 19 } 20 21 //合并函数 22 void Merge(int a[], int l, int m, int r) 23 { 24 int i = l, j = m+1, k = l; 25 int b[N]; 26 while(i <= m && j <= r) 27 { 28 if(a[i] <= a[j]) 29 { 30 b[k++] = a[i++]; 31 } 32 else 33 { 34 b[k++] = a[j++]; 35 } 36 } 37 38 if(i > m) 39 { 40 for(int p = j; p <= r; p++) 41 { 42 b[k++] = a[p]; 43 } 44 } 45 else 46 { 47 for(int p = i; p <= m; p++) 48 { 49 b[k++] = a[p]; 50 } 51 } 52 53 //把b[]中排好的元素copy到a[]中 54 for(int q = l; q <= r; q++) 55 { 56 a[q] = b[q]; 57 } 58 } 59 60 //并归排序 递归算法表示 61 void MergeSort(int a[], int left, int right) 62 { 63 if(left < right) //数组中至少有两个元素 64 { 65 int i = (right + left)/2; 66 MergeSort(a, left, i); 67 MergeSort(a, i+1, right); 68 Merge(a, left, i, right);//把left到right的元素排好序 69 } 70 } 71 72 //打印排好序的数组 73 void Print() 74 { 75 cout << "经过MergeSort后:"; 76 for(int i = 0; i < count; i++) 77 { 78 cout << g_array[i] << " "; 79 } 80 cout << endl; 81 } 82 83 int main() 84 { 85 Initial(); 86 if(count > 1) 87 { 88 MergeSort(g_array, 0, count-1); 89 Print(); 90 } 91 else if(count == 1) 92 { 93 Print(); 94 } 95 system("pause"); 96 return 0; 97 }