您的位置:首页 > 其它

HDU 2020 绝对值排序

2015-01-21 20:38 211 查看
Description

输入n(n<=100)个整数,按照绝对值从大到小排序后输出。题目保证对于每一个测试实例,所有的数的绝对值都不相等。

Input

输入数据有多组,每组占一行,每行的第一个数字为n,接着是n个整数,n=0表示输入数据的结束,不做处理。

Output

对于每个测试实例,输出排序后的结果,两个数之间用一个空格隔开。每个测试实例占一行。

Sample Input

3 3 -4 2
4 0 1 2 -3
0


Sample Output

-4 3 2
-3 2 1 0


手写快排,然后直接修改快排内部比较的代码为绝对值比较就可以了,代码如下:

#include <iostream>
#include <fstream>

using namespace std;

typedef int type;
int abs(int a)	//我也忘了我为什么要手写abs。。。
{
if(a<0)
a=-a;
return a;
}
void sort(type *begin,type *end)
{
end--;
if(begin<end)
{
type *key=begin;
type *low=begin;
type *high=end;
while(low<high)
{
while(low<high&&abs(*high)>=abs(*key))	//全部改为绝对值比较
high--;
while(low<high&&abs(*low)<=abs(*key))
low++;
swap(*low,*high);
}
swap(*key,*low);
sort(begin,low);
sort(low+1,end+1);
}
}

int main()
{
ios::sync_with_stdio(false);
//	fstream cin("in.in");
int num[101];
int n;
while(cin>>n,n)
{
for(int i=0;i<n;i++)
cin>>num[i];
sort(num,num+n);
for(int i=n-1;i>=0;i--)
{
cout<<num[i];
if(i!=0)
cout<<" ";
else
cout<<endl;
}
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: