题目描述
归并排序是一个时间复杂度为O(nlogn)的算法,对于大量数据远远优于冒泡排序与插入排序。 这是一道排序练习题,数据量较大,请使用归并排序完成。输入
第一行一个数字n,代表输入的组数
其后每组第一行输入一个数字m,代表待排序数字的个数
其后m行每行一个数据,大小在1~100000之间,互不相等,最多有10万个数据。
输出
升序输出排好序的数据,每行一个数字
输入样例
1
10
10
9
8
7
6
5
4
3
2
1
输出样例
1
2
3
4
5
6
7
8
9
10
解题过程
- 题目理解
- 程序框架搭建
- 程序实现
题目理解
用归并序列实现,n是第一行一个数字,其后m行每行一个数据其后每组第一行输入一个数字m,代表待排序数字的个数
程序框架搭建
分块处理
从主函数开始
int main()
{
int n,m,a[maxn];
while(scanf("%d",&n)!=EOF)
{
while(scanf("%d",&m)!=EOF)
{
for(int j=0;j<m;j++)
{
scanf("%d",&a[j]);
}
mergeSort(a,0,m-1);
for(int j=0;j<m;j++)
{
printf("%d\n",a[j]);
}
}
}
return 0;
}
递归排序
void mergeSort(int a[],int left,int right)//将数组当前区间[left,right]进行归并排序
{
if(left<right)//left和right不能相遇
{
int mid = (left+right)/2;//取中点
mergeSort(a,left,mid);//递归,左子区间归并排序
mergeSort(a,mid+1,right);//递归,右子区间归并排序
merge(a,left,mid,mid+1,right);//将左子区间和右子区间排序
}
}
排序
void merge(int a[],int L1,int R1,int L2,int R2)
{
int i=L1,j=L2;//i指向A[L1],j指向A[L2]
int temp[maxn],index=0;//temp临时存放合并后的数组,index为下标
while(i<=R1&&j<=R2)
{
if(a[i]<=a[j])//如果a[i]小于a[j]
temp[index++]=a[i++];//a[i]加入temp
else
temp[index++]=a[j++];
}
//将剩余的元素加入temp
while(i<=R1)
{
temp[index++]=a[i++];
}
while(j<=R2)
{
temp[index++]=a[j++];
}
for(int i=0;i<index;i++)
{
a[L1+i]=temp[i];
}
}
#include<stdio.h>
const int maxn=100010;
void merge(int a[],int L1,int R1,int L2,int R2)
{
int i=L1,j=L2;//i指向A[L1],j指向A[L2]
int temp[maxn],index=0;//temp临时存放合并后的数组,index为下标
while(i<=R1&&j<=R2)
{
if(a[i]<=a[j])//如果a[i]小于a[j]
temp[index++]=a[i++];//a[i]加入temp
else
temp[index++]=a[j++];
}
//将剩余的元素加入temp
while(i<=R1)
{
temp[index++]=a[i++];
}
while(j<=R2)
{
temp[index++]=a[j++];
}
for(int i=0;i<index;i++)
{
a[L1+i]=temp[i];
}
}
void mergeSort(int a[],int left,int right)//将数组当前区间[left,right]进行归并排序
{
if(left<right)//left和right不能相遇
{
int mid = (left+right)/2;//取中点
mergeSort(a,left,mid);//递归,左子区间归并排序
mergeSort(a,mid+1,right);//递归,右子区间归并排序
merge(a,left,mid,mid+1,right);//将左子区间和右子区间排序
}
}
int main()
{
int n,m,a[maxn];
while(scanf("%d",&n)!=EOF)
{
while(scanf("%d",&m)!=EOF)
{
for(int j=0;j<m;j++)
{
scanf("%d",&a[j]);
}
mergeSort(a,0,m-1);
for(int j=0;j<m;j++)
{
printf("%d\n",a[j]);
}
}
}
return 0;
}