一.自己的代码
1.源码
#include<stdio.h>
#define N 100
void merge(int a[],int left,int right,int mid){
int temp[N];
int l_pos=left,r_pos=mid+1;
int pos=left;
while(l_pos<=mid&&r_pos<=right){
if(a[l_pos]<a[r_pos]) temp[pos++]=a[l_pos++];
else temp[pos++]=a[r_pos++];
}
while(l_pos<=mid) temp[pos++]=a[l_pos++];
while(r_pos<=right) temp[pos++]=a[r_pos++];
while(left<=right){
a[left]=temp[left];
left++;
}
}
void mergeSort(int a[],int left,int right){
if(left<right){
int mid=(left+right)/2;
mergeSort(a,left,mid);
mergeSort(a,mid+1,right);
merge(a,left,right,mid);
}
}
int main(){
int a[N];
int n;
scanf("%d",&n);
for(int i=0;i<n;i++)
scanf("%d",a+i);
mergeSort(a,0,n-1);
for(int i=0;i<n;i++)
printf("%d ",a[i]);
}
2.测试
2.1测试数据
9
1 3 2 2 5 4 77 4 1
2.2结果
![](https://img2023.cnblogs.com/blog/2177087/202302/2177087-20230214184728541-485538557.png)
二.y总的模板
#include<iostream>
using namespace std;
const int N=100;
void mergeSort(int a[],int left,int right){
if(left<right){
int mid =(left+right)/2;
mergeSort(a,left,mid);
mergeSort(a,mid+1,right);
int temp[N],l_pos=left,r_pos=mid+1,pos=left;
while(l_pos<=mid&&r_pos<=right){
if(a[l_pos]<a[r_pos]) temp[pos++]=a[l_pos++];
else temp[pos++]=a[r_pos++];
}
while(l_pos<=mid) temp[pos++]=a[l_pos++];
while(r_pos<=right) temp[pos++]=a[r_pos++];
for(int i=left;i<=right;i++) a[i]=temp[i];
}
}
int main(){
int n;
int a[N];
scanf("%d",&n);
for(int i=0;i<n;i++)
scanf("%d",a+i);
mergeSort(a,0,n-1);
for(int i=0;i<n;i++)
printf("%d ",a[i]);
return 0;
}