輸入三個整數,輸出由小到大排序結果。本文展示交換排序法邏輯,並分析其與冒泡、選擇排序的關聯。
輸入 x, y, z,輸出升序序列。
import java.util.Scanner;
public class ThreeNumberSort {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("請輸入三個整數(空格分隔):");
int x = sc.nextInt();
int y = sc.nextInt();
int z = sc.nextInt();
sc.close();
// 確保 x 最小
if (x > y) { int t = x; x = y; y = t; }
if (x > z) { int t = x; x = z; z = t; }
// 確保 y <= z
if (y > z) { int t = y; y = z; z = t; }
System.out.printf("排序結果:%d, %d, %d%n", x, y, z);
}
}
請輸入三個整數(空格分隔):30 10 20 排序結果:10, 20, 30
| 方法 | 程式碼 | 優點 |
|---|---|---|
| Arrays.sort | int[] a = {x,y,z}; Arrays.sort(a); | 標準庫、可讀性高、支援任意長度 |
| Stream API | IntStream.of(x,y,z).sorted().toArray() | 函數風格、易併行 |
| Collections.sort | List.of(x,y,z).stream().sorted().toList() | 物件型別、不可變列表 |
| 手寫冒泡 | 雙層迴圈相鄰比較交換 | 教學示範排序原理 |
三數排序是理解比較交換邏輯的入門範例。實務開發中,優先使用 Arrays.sort 或 Stream API,僅在嵌入式、面試或教學場景手寫排序邏輯。