輸入多組測試數據,每組第一個整數 n (≤100),後跟 n 個整數。按絕對值從大到小排序輸出。保證絕對值互不相同。n=0 結束輸入。
Java 中使用 Arrays.sort 搭配 Comparator,比較邏輯為 |b| - |a|(降序)。
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
int n = in.nextInt();
if (n == 0) break;
Integer[] arr = new Integer[n];
for (int i = 0; i < n; ++i) arr[i] = in.nextInt();
Arrays.sort(arr, (a, b) -> Math.abs(b) - Math.abs(a));
for (int i = 0; i < n; ++i) {
if (i) System.out.print(' ');
System.out.print(arr[i]);
}
System.out.println();
}
}
}
Integer[] 而非 int[] 以支援 Comparator(a, b) -> Math.abs(b) - Math.abs(a) 實現降序n=0 終止,Scanner.hasNext() 處理多組數據輸入: 3 3 -4 2 4 0 1 2 -3 0 輸出: -4 3 2 -3 2 1 0