在程式設計的入門階段,數列排序是最經典且基礎的練習題目之一。這道題目要求將一個長度為 n 的整數數列,依照從小到大的順序進行排序輸出。雖然現代程式語言都內建了高效的排序函式,但理解其背後的邏輯與實作方式,對於建立扎實的演算法基礎至關重要。
5 以及 8 3 6 4 9,輸出應為 3 4 6 8 9。利用 Java 標準庫 Arrays.sort() 即可輕鬆解決,該方法底層採用雙軸快速排序,對於 n ≤ 200 的小規模資料效能極佳。
import java.util.Arrays;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (scan.hasNextInt()) {
int n = scan.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = scan.nextInt();
}
Arrays.sort(arr);
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
}
}
若在面試或競賽中被要求「手寫排序」,建議掌握快速排序或合併排序,兩者平均時間複雜度均為 O(n log n),且合併排序具備穩定性。對於極小規模資料,插入排序反而因常數因子小而更快。理解各種排序的適用場景,才是演算法學習的核心價值。