diff --git a/codes/w18515601045/19446136.java b/codes/w18515601045/19446136.java new file mode 100644 index 0000000000000000000000000000000000000000..0b30956fc74499eadcd5be083e815f9ab3da47eb --- /dev/null +++ b/codes/w18515601045/19446136.java @@ -0,0 +1,49 @@ +public class BubbleSortExample { + + /** + * 冒泡排序函数 + * aa bb cc + * @param a 待排序的数组 + * @param n 待排序的数组长度 + */ + public static void bubbleSort(int[] a, int n) { + // 外层循环控制排序的轮数,总共需要进行 n - 1 轮 + for (int i = 0; i < n - 1; i++) { + // 标记本轮是否发生了交换,若未发生交换说明数组已经有序 + boolean swapped = false; + // 内层循环进行相邻元素的比较和交换 + for (int j = 0; j < n - i - 1; j++) { + // 如果当前元素比下一个元素大,则交换它们的位置 + if (a[j] > a[j + 1]) { + int temp = a[j]; + a[j] = a[j + 1]; + a[j + 1] = temp; + // 发生了交换,将标记置为 true + swapped = true; + } + } + // 如果本轮没有发生交换,说明数组已经有序,提前结束排序 + if (!swapped) { + break; + } + } + } + + public static void main(String[] args) { + int[] a = {5, 3, 8, 4, 2}; + int n = a.length; + System.out.println("排序前的数组:"); + for (int num : a) { + System.out.print(num + " "); + } + System.out.println(); + + // 调用冒泡排序方法 + bubbleSort(a, n); + + System.out.println("排序后的数组:"); + for (int num : a) { + System.out.print(num + " "); + } + } +}