绝对值排序
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 38025 Accepted Submission(s): 18618
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
分析
本题考查的是排序。数据“按照绝对值从大到小排序后输出”,这和我们的自然数大小规则不一样,说明我们需要自定义一个数据大小的比较规则,然后再采用排序算法进行排序
算法代码
import java.util.Scanner;
public class Main {
// 自定义比较规则
static boolean cmp(int a, int b) {
if (Math.abs(a) < Math.abs(b)) return true;
else return false;
}
// 冒泡排序
static int[] sort(int[] arr) {
for (int i = arr.length - 1; i > 0; i--) {
for (int j = 0; j < i; j++) {
if (cmp(arr[j], arr[j + 1])) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
return arr;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()) {
int n = scanner.nextInt();
if (n == 0) return;
int[] nums = new int[n];
for (int i = 0; i < n; i++) nums[i] = scanner.nextInt();
nums = sort(nums);
for (int i = 0; i < nums.length - 1; i++) System.out.print(nums[i] + " ");
System.out.println(nums[n - 1]);
}
}
}