此博客链接:https://www.cnblogs.com/ping2yingshi/p/12266997.html
绝对值排序(37min)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2020
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
题解:此题就是一个从大到小排序,但是在排序时要考虑有负数情况,所以在排序时要先分几种情况然后再判断数值大小,这里我选择的选择排序,一共分为四种情况,第一种:比较的两个数都是正数,直接比较大小,选大数下标;第二种:排序的两个数都是负数,直接比较大小,选小数下标;第三种:排序的两个数,前一个数是负数,后一个数是正数,对负数取反和正数比较大小,选大数下标;第四种:排序的两个数,前一个数是正数,后一个数是负数,对负数取反和正数比较大小,选大数下标。我主要是把选择排序的内层循环写错了,把j=i写成了j=0了,单步循环找了好久,才发现。哎,脑子是个好东西,可是我脑子呢?
代码如下:
#include<stdio.h> #include<math.h> #include<stdlib.h> int main(void) { int n; while(~scanf("%d",&n)) { if(n==0) break; int i; int j; int k; int temp; int c[100]; for(i=0;i<n;i++) { scanf("%d",&c[i]); } for(i=0;i<n-1;i++) { k=i; for(j=i+1;j<n;j++) { if((c[j]<0 )&&(c[k]<0)) { if(c[j]<c[k]) k=j; } else if((c[j]>=0 )&&(c[k]>=0)) { if(c[j]>c[k]) k=j; } else if((c[j]>0 )&&(c[k]<0)) { if(c[j]>-c[k]) k=j; } else if((c[j]<0 )&&(c[k]>0)) { if(-c[j]>c[k]) k=j; } } temp=c[i]; c[i]=c[k]; c[k]=temp; } for(i=0;i<n-1;i++) printf("%d ",c[i]); printf("%d",c[n-1]); printf(" "); } return 0; }