public class BubbleSort { public static void sort(int[] arr) { if (arr == null || arr.length <= 1) return; int n = arr.length; boolean swapped; // 优化标志:若某轮无交换,说明已有序 for (int i = 0; i < n - 1; i++) { // 外层循环:n-1轮 swapped = false; for (int j = 0; j < n - 1 - i; j++) { // 内层循环:每轮确定第i大元素 if (arr[j] > arr[j + 1]) { // 交换相邻元素 int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; swapped = true; } } if (!swapped) break; // 提前终止:若某轮无交换,直接结束 } } public static void main(String[] args) { int[] arr = {64, 34, 25, 12, 22, 11, 90}; sort(arr); System.out.println("排序后数组:"); for (int num : arr) { System.out.print(num + " "); // 输出:11 12 22 25 34 64 90 } } }