绝对值排序
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 25869 Accepted Submission(s): 12720
Problem 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
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 25869 Accepted Submission(s): 12720
Problem 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 <stdio.h>
int abs(int x){
return x>0 ? x : -x;
}
int compare(const void *a, const void *b){
int c = abs(*(int*)a);
int d = abs(*(int*)b);
if ( c > d ){
return 1;
}
else if ( c < d ){
return -1;
}
else {
return 0;
}
}
int partition(int a[], int x, int y, int (*compare)(const void*, const void*)){
int t = a[x];
while ( x < y ){
while ( x<y && ((*compare)(&a[y], &t))<0 ) --y;
a[x] = a[y];
while ( x<y && ((*compare)(&a[x], &t))>0 ) ++x;
a[y] = a[x];
}
a[x] = t;
return x;
}
void myqsort(int a[], int x, int y, int (*compare)(const void*, const void*)){
if ( x >= y ){
return;
}
int p = partition(a, x, y, compare);
myqsort(a, x, p-1, compare);
myqsort(a, p+1, y, compare);
}
int main(){
int a[101];
int n, i;
while ( ~scanf("%d", &n) && n ){
for ( i=0; i<n; ++i ){
scanf("%d", a+i);
}
myqsort(a, 0, n-1, compare);
printf("%d", a[0]);
for ( i=1; i<n; ++i ){
printf(" %d", a[i]);
}
printf("\n");
}
return 0;
}