From 5fee2fde8c7efddaff0086362ecdb100650dbb47 Mon Sep 17 00:00:00 2001 From: CoritePirous <3386886739@qq.com> Date: Mon, 7 Apr 2025 13:40:52 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E6=8E=92=E5=BA=8F=E4=BB=A3?= =?UTF-8?q?=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- codes/CoritePirous/20108382.java | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 codes/CoritePirous/20108382.java diff --git a/codes/CoritePirous/20108382.java b/codes/CoritePirous/20108382.java new file mode 100644 index 00000000..450fd856 --- /dev/null +++ b/codes/CoritePirous/20108382.java @@ -0,0 +1,29 @@ +/** + * 冒泡排序函数 + * aa bb cc + * @param a 待排序的数组 + * @param n 待排序的数组长度 + */ +public static void bubbleSort(int[] a, int n) { + // 循环遍历数组中的所有元素 + for (int i = 0; i < n - 1; i++) { + // 标记这一轮是否进行了交换 + boolean swapped = false; + // 内层循环,进行相邻元素的比较和交换 + for (int j = 0; j < n - 1 - i; j++) { + // 如果前面的元素比后面的大,交换它们 + if (a[j] > a[j + 1]) { + int temp = a[j]; + a[j] = a[j + 1]; + a[j + 1] = temp; + // 发生了交换,更新标记 + swapped = true; + } + } + // 如果这一轮没有发生交换,说明数组已经有序,可以提前结束排序 + if (!swapped) { + break; + } + } +} // end bubbleSort + -- Gitee