归并排序(递归)
作者:
高歌猛进
,
2024-08-03 22:52:34
,
所有人可见
,
阅读 2
#include<stdio.h>
void MergeSort(int a[],int low,int high){
if(low<high){
int mid = (low+high)/2;
MergeSort(a,low,mid); //遍历左边序列
MergeSort(a,mid+1,high); //遍历右边序列
merge(a,low,mid,high); // 将左右两序列进行合并
}
}
void merge(int a[],int low,int mid,int high){
int b[high-low+1]; //定义临时数组b存放数组a的值
int i = low; //i为左端开始
int j = mid+1;//j为右端开始
int k = 0;//b数组索引从0开始
while(i <= mid && j <= high){ //遍历左右两序列,依次将值小的放入b数组
if(a[i]<a[j])
b[k++] = a[i++];
else
b[k++] = a[j++];
}
while(i <= mid) b[k++] = a[i++];//处理未完成的元素
while(j <= high) b[k++] = a[j++];
for(i=low,k=0;i<=high;i++,k++) a[i] = b[k]; //将b数组的值复制到a数组
}
int main(){
int n;
scanf("%d",&n);
int a[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]);
}