堆排序 hdu 2020 绝对值排序

来源:互联网 发布:三星电话交换机编程 编辑:程序博客网 时间:2024/06/05 17:12

绝对值排序

TimeLimit: 2000/1000 MS(Java/Others)    MemoryLimit: 65536/32768 K (Java/Others)
Total Submission(s):15473    AcceptedSubmission(s): 7661


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

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

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

Sample Input
3 -42 
4 0 12 -3 
0
 

Sample Output
-4 3 2 
-3 2 1 0
#include<stdio.h>
#include<stdlib.h>
struct node
{
int x;
int y;
}data[1000];
void creatheap(struct node *heap,int root,int len)
{
int done;
int j;
struct node temp;
j=2*root;
temp=heap[root];
done=0;
while(j<=len&&!done)
{
if(j<len)
if(heap[j].y<heap[j+1].y)
j++;
if(temp.y>=heap[j].y)
done=1;
else
{
heap[j/2]=heap[j];
j=2*j;
}
}
heap[j/2]=temp;
}
void heap(struct node *heap,int len)
{
int i;
struct node temp;
for(i=(len/2);i>=1;i--)
creatheap(heap,i,len);
for(i=len-1;i>=1;i--)
{
temp=heap[i+1];
heap[i+1]=heap[1];
heap[1]=temp;
creatheap(heap,1,i);

}

}
void main()
{
   inti,n; 
  while(scanf("%d",&n)!=EOF,n)
   {
  for (i =1; i<=n;i++ )    
   {
 scanf("%d",&data[i].x);
 data[i].y=data[i].x>=0?-data[i].x:data[i].x;
   }
  heap(data,n); 
     for (i=1; i<n;i++ )    
     printf("%d ",data[i].x);
  printf("%d\n",data[i].x); 
   }
}