合并排序(swust oj 446)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_25735003/article/details/89007218

这是一个很简单的排序题目. 为了锻炼大家对不同算法的了解,请大家用归并排序法对此题进行解答. 对一组整数数列A[1],A[2],A[3]......A[N]进行排序,按照从小到大的顺序输出.

输入

本题只有一组测试数据,在输入的第一行输入N(表示整数数列的大小)(N < 1000)
接下来N行输入N个整数,每一行一个整数.

输出

对已经排好序的数从小到大依次输出,每两个数之间用两个空格隔开,且每输出10个数换行.

样例输入

12
45 
545 
48 
47 
44 
45 
4857 
58 
57 
485 
1255 
42

样例输出

42 44 45 45 47 48 57 58 485 545
1255 4857

关于解题的思路在代码里已经有体现了,大概思路,我就列了一个导向图来表示

#include"iostream"
#include"stdio.h"
#include"cmath"
#include"cstring"
#include"algorithm"
using namespace std;
void merge(int a[],int left,int mid,int right,int temp[])
{
	int i = left;
	int j = mid + 1;                //避免重复比较a[mid]
	int t = 0;
	while(i <= mid && j <= right)  //数组a[left,mid]与数组(mid,right]均没有全部归入数组temp中去
	{
		if(a[i] <= a[j])           //如果a[i]小于等于a[j]
			temp[t++] = a[i++];     //则将a[i]的值赋给temp[k],之后i,k各加一,表示后移一位
		else
			temp[t++] = a[j++];    //否则,将a[j]的值赋给temp[k],j,k各加一
	}
	  /*表示数组a(mid,right]已经全部归入temp数组中去了,而数组a[left,mid]还有剩余      */
	while(i <= mid)         
		temp[t++] = a[i++];     //将数组a[left,mid]剩下的值,逐一归入数组temp
	while(j <= right)            //表示数组a[left,mid]已经全部归入到temp数组中去了,而数组(mid,high]还有剩余
		temp[t++] = a[j++];       //将数组a[mid,high]剩下的值,逐一归入数组temp
	for(i = 0; i < t; i++)          //将归并后的数组的值逐一赋给数组a[left,right]
		a[left+i] = temp[i];
}
void sort(int temp[],int a[],int left,int right)
{
	if(left < right)
	{
		int mid = left + (right - left) / 2;
		sort(temp,a,left,mid);     //先把左边排序 
		sort(temp,a,mid + 1,right);  //右边排序 
		merge(a,left,mid,right,temp);  //合并到一起 
	}
}
int main()
{
	int num;
	cin >> num;
	int a[num] = {0};
	for(int i = 0; i < num; i++)
	{
		cin >> a[i];
	}
//	for(int i = 0; i < num; i++)
//	{
//		cout << a[i] <<" ";
//	}
	int temp[num] = {0};
	sort(temp,a,0,num-1);
	int i;
	for(i = 0; i < num - 1; i++)
	{
		if((i + 1) % 10 == 0)
			cout << a[i] << endl;
		else 
			cout << a[i] <<"  ";   //这里是两个空格 
	}
	cout << a[i] << endl;
}

猜你喜欢

转载自blog.csdn.net/qq_25735003/article/details/89007218