HDU ACM STEP 1.3.8 As Easy As A+B

As Easy As A+B

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 4137 Accepted Submission(s): 1895
 
Problem Description
These days, I am thinking about a question, how can I get a problem as easy as A+B? It is fairly difficulty to do such a thing. Of course, I got it after many waking nights.
Give you some integers, your task is to sort these number ascending (升序).
You should know how easy the problem is now!
Good luck!
 
Input
Input contains multiple test cases. The first line of the input is a single integer T which is the number of test cases. T test cases follow. Each test case contains an integer N (1<=N<=1000 the number of integers to be sorted) and then N integers follow in the same line. 
It is guarantied that all integers are in the range of 32-int.
 
Output
For each case, print the sorting result, and one line one case.
 
Sample Input
2
3 2 1 3
9 1 4 7 2 5 8 3 6 9
 
Sample Output
1 2 3
1 2 3 4 5 6 7 8 9
 

题目比较简单,就是一个升序排序,基本没有坑位,除了输出结果最后的一个数字后面记得不能加空格。。。

这里使用快速排序解决问题。


#include <iostream>

using namespace std;


void QuickSort(int *a, int low, int high)
{
	if (high - low <= 1e-6)
		return;

	int first = low;
	int last = high;
	int key = a[first];

	while (first < last)
	{
		while (first < last && a[last] >= key)
		{
			last--;
		}
		a[first] = a[last];

		while (first < last && a[first] <= key)
		{
			first++;
		}
		a[last] = a[first];
	}
	a[first] = key;
	QuickSort(a, low, first - 1);
	QuickSort(a, first + 1, high);

}

void main()
{
	int n;
	cin >> n;

	for (int i = 0;i < n;i++)
	{
		int num;
		cin >> num;

		int *a = new int[num];

		for (int j = 0;j < num;j++)
			cin >> a[j];

		QuickSort(a, 0, num-1);

		for (int k = 0; k < num-1; k++)
			printf("%d ", a[k]);
		printf("%d", a[num-1]);
		cout << endl;
	}
}
顺便回忆一下快速排序的思想。
选定一个参考数字key,一般就选择数组第一个数字。
将小于key的移到key前面,大于key的移到key后面。
while (first < last)
	{
		while (first < last && a[last] >= key)
		{
			last--;
		}
		a[first] = a[last];

		while (first < last && a[first] <= key)
		{
			first++;
		}
		a[last] = a[first];
	}
a[first] = key;
	QuickSort(a, low, first - 1);
	QuickSort(a, first + 1, high);

 思路讲解: 
     
例如,待排序的数组为2 5 4 1 3.
先选定2为key,然后从最后面出发寻找小于2的数字,此处为1.
while (first < last && a[last] >= key)
		{
			last--;
		}

结束后,first=0,last=3,然后
a[first] = a[last];
此时数组变成,1 5 4 1 3,这里第四个1可以看做是个空,下一步要找到一个比2大的数字填到这个坑。
while (first < last && a[first] <= key)
		{
			first++;
		}
		a[last] = a[first];
上面的代码,first=1,last=3,因此执行后数组为1 5 4 5 3,这里可以看做第一个5是个空,下一步要找到比2小的数字填坑。
继续循环执行
while (first < last && a[last] >= key)
		{
			last--;
		}
a[first] = a[last];
last为0,first为1,数据变成1 1 4 5 3,
 
      
然后下一步相同,退出while循环,来到后面步骤,此时最后一个待填入的位置为a[first],把key值填入,完成一次排序操作。之后对key的左右两边分别进行排序,递归,递归结束条件为子数组长度为1.
a[first] = key;
	QuickSort(a, low, first - 1);
	QuickSort(a, first + 1, high);

 
     

猜你喜欢

转载自blog.csdn.net/qq_39459939/article/details/79074691