From 139d66c478ca5c7dc784d9b20bfcadc40f1e1023 Mon Sep 17 00:00:00 2001 From: "yuechao.zhao" Date: Tue, 14 Oct 2025 11:15:43 +0800 Subject: [PATCH] =?UTF-8?q?=E6=8E=92=E5=BA=8F=E5=88=9D=E7=89=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- codes/yuechao123/21917030.java | 89 ++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 codes/yuechao123/21917030.java diff --git a/codes/yuechao123/21917030.java b/codes/yuechao123/21917030.java new file mode 100644 index 00000000..2a37106d --- /dev/null +++ b/codes/yuechao123/21917030.java @@ -0,0 +1,89 @@ +import java.util.Arrays; +import java.util.Scanner; + +class BubbleSort { + + // 优化的冒泡排序算法 + public static void bubbleSort(int[] arr) { + int n = arr.length; + boolean swapped; + + for (int i = 0; i < n - 1; i++) { + swapped = false; + + // 每轮将最大元素移动到末尾 + for (int j = 0; j < n - i - 1; j++) { + 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 int[] generateRandomArray(int size) { + int[] array = new int[size]; + for (int i = 0; i < size; i++) { + array[i] = (int)(Math.random() * 100); // 0-99的随机数 + } + return array; + } + + // 主程序 + public static void main(String[] args) { + Scanner scanner = new Scanner(System.in); + + System.out.println("📊 冒泡排序程序"); + System.out.println("1️⃣ 随机生成数组并排序"); + System.out.println("2️⃣ 手动输入数组并排序"); + System.out.print("选择选项 (1-2): "); + + int choice = scanner.nextInt(); + int[] array; + int size; + + switch(choice) { + case 1: + System.out.print("➡️ 请输入数组大小: "); + size = scanner.nextInt(); + array = generateRandomArray(size); + break; + + case 2: + System.out.print("➡️ 请输入数组元素个数: "); + size = scanner.nextInt(); + array = new int[size]; + System.out.println("➡️ 请输入" + size + "个整数:"); + for (int i = 0; i < size; i++) { + array[i] = scanner.nextInt(); + } + break; + + default: + System.out.println("❌ 无效选择,使用随机数组"); + array = generateRandomArray(10); + size = 10; + } + + // 显示原始数组 + System.out.println("\n🔢 原始数组: " + Arrays.toString(array)); + + // 执行排序并计时 + long startTime = System.nanoTime(); + bubbleSort(array); + long endTime = System.nanoTime(); + + // 显示结果 + System.out.println("🆙 排序数组: " + Arrays.toString(array)); + double duration = (endTime - startTime) / 1e6; // 转换为毫秒 + System.out.printf("⏰ 排序耗时: %.3f 毫秒\n", duration); + System.out.println("\n🎉 排序完成!"); + } +} -- Gitee