1. 冒泡排序
- 遍历数组,每一次循环,两两比较,大的放后面
- 每次 outerloop 遍历就会让当前没有 sorted 部分找出一个最大元素放到正确的位置上 (被换到那)
严格的
O(N^2)
时间复杂度,两个两个元素进行比较它的基本思想是反复地交换相邻的未按顺序排列的元素。
代码演示
冒泡排序算法的示例代码:
javaCopy codepublic class BubbleSort {public static void bubbleSort(int[] arr) {int n = arr.length;for (int i = 0; i < n - 1; i++) {for (int j = 0; j < n - i - 1; j++) {if (arr[j] > arr[j + 1]) {// 交换arr[j]和arr[j + 1]的位置int temp = arr[j];arr[j] = arr[j + 1];arr[j + 1] = temp;}}}}public static void main(String[] args) {int[] arr = {64, 34, 25, 12, 22, 11, 90};System.out.println("原始数组:");printArray(arr);bubbleSort(arr);System.out.println("排序后的数组:");printArray(arr);}public static void printArray(int[] arr) {for (int i : arr) {System.out.print(i + " ");}System.out.println();}}javaCopy codepublic class BubbleSort { public static void bubbleSort(int[] arr) { int n = arr.length; for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - i - 1; j++) { if (arr[j] > arr[j + 1]) { // 交换arr[j]和arr[j + 1]的位置 int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } public static void main(String[] args) { int[] arr = {64, 34, 25, 12, 22, 11, 90}; System.out.println("原始数组:"); printArray(arr); bubbleSort(arr); System.out.println("排序后的数组:"); printArray(arr); } public static void printArray(int[] arr) { for (int i : arr) { System.out.print(i + " "); } System.out.println(); } }javaCopy codepublic class BubbleSort { public static void bubbleSort(int[] arr) { int n = arr.length; for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - i - 1; j++) { if (arr[j] > arr[j + 1]) { // 交换arr[j]和arr[j + 1]的位置 int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } public static void main(String[] args) { int[] arr = {64, 34, 25, 12, 22, 11, 90}; System.out.println("原始数组:"); printArray(arr); bubbleSort(arr); System.out.println("排序后的数组:"); printArray(arr); } public static void printArray(int[] arr) { for (int i : arr) { System.out.print(i + " "); } System.out.println(); } }
这段代码定义了一个名为BubbleSort
的类,其中包含了一个静态方法bubbleSort
用于执行冒泡排序算法。在main
方法中,我们创建了一个整数数组arr
,调用bubbleSort
方法对其进行排序,并通过printArray
方法打印排序后的数组。
冒泡排序算法的核心思想是通过相邻元素的比较和交换,将较大的元素逐渐“冒泡”到数组的末尾。外层循环控制需要进行比较的轮数,内层循环在每一轮中依次比较相邻的两个元素并交换位置。
输出结果将会是:
makefileCopy code原始数组:64 34 25 12 22 11 90排序后的数组:11 12 22 25 34 64 90makefileCopy code原始数组: 64 34 25 12 22 11 90 排序后的数组: 11 12 22 25 34 64 90makefileCopy code原始数组: 64 34 25 12 22 11 90 排序后的数组: 11 12 22 25 34 64 90
© 版权声明
文章版权归作者所有,未经允许请勿转载,侵权请联系 admin@trc20.tw 删除。
THE END