1 #include <iostream>
2 using namespace std;
3 const int maxn = 100;
4
5 int merge(int A[],int L1,int R1,int L2,int R2){//L1、R1为第一段区间的左下标与右下标,同理L2、R2 为第二段……
6
7 int temp[maxn]={0},index=0;
8 int i=L1,j=L2;
9
10 while(i<=R1 && j<=R2){//两段数据做对比,将较小的放入temp数组中
11 if(A[i]<=A[j]){
12 temp[index++]=A[i++];
13 }else{
14 temp[index++]=A[j++];
15 }
16 }
17 while(i<=R1){//将第一段中剩余的元素 放入temp数组中
18 temp[index++]=A[i++];
19 }
20 while(j<=R2){//将第二段中剩余的元素 放入temp数组中
21 temp[index++]=A[j++];
22 }
23
24 for(int i=0;i<index;i++){//将temp数组中的 元素放进 A数组中
25 A[L1+i]=temp[i];
26 }
27 }
28
29 //递归实现
30 void mergesort(int A[],int left,int right){
31
32
33 if(left<right){
34
35 int mid = (left+right)/2;
36 mergesort(A,left,mid);
37 mergesort(A,mid+1,right);
38 merge(A,left,mid,mid+1,right);
39
40 }
41
42 }
43
44 int main(){
45 int num[7]={5,4,7,1,2,3,9};
46 mergesort(num,0,6);
47 for(int i=0;i<7;i++){
48 cout<<num[i]<<'\n';
49 }
50 return 0;
51 }