冒泡排序 发表于 2019-04-29 | 更新于 2019-05-02 | 分类于 算法 | 评论数: | 阅读次数: 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103public class BubbleSortDemo { public static void main(String[] args) { // 定义一个数组 int[] arr = {24, 69, 80, 57, 13} ; // 遍历方法 System.out.print("排序前: "); print(arr) ; // 排序 bubbleSort2(arr); // 排序后的输出 System.out.print("排序后: "); print(arr) ; } /** * 优化后的冒泡排序 */ private static void bubbleSort2(int[] arr) { for(int x = 0 ; x < arr.length - 1 ; x++){ /* * arr.length - 1: 目的是为了防止数组角标越界 * arr.length - 1 - x : -x目的是为了提高效率 */ for(int y = 0 ; y < arr.length - 1 - x ; y++){ if(arr[y] > arr[y + 1]){ int temp = arr[y] ; arr[y] = arr[y+1]; arr[y+1] = temp ; } } } } /** * 冒泡排序 */ private static void bubbleSort(int[] arr) { // 第一次排序 // arr.length - 1 目的: 防止数组角标越界 for(int x = 0 ; x < arr.length - 1 - 0; x++){ if(arr[x] > arr[ x + 1 ]){ int temp = arr[x] ; arr[x] = arr[ x + 1]; arr[ x + 1 ] = temp ; } } // 第二次排序 for(int x = 0 ; x < arr.length - 1 - 1; x++){ if(arr[x] > arr[ x + 1 ]){ int temp = arr[x] ; arr[x] = arr[ x + 1]; arr[ x + 1 ] = temp ; } } // 第三次排序 for(int x = 0 ; x < arr.length - 1 - 2; x++){ if(arr[x] > arr[ x + 1 ]){ int temp = arr[x] ; arr[x] = arr[ x + 1]; arr[ x + 1 ] = temp ; } } // 第四次排序 for(int x = 0 ; x < arr.length - 1 - 3; x++){ if(arr[x] > arr[ x + 1 ]){ int temp = arr[x] ; arr[x] = arr[ x + 1]; arr[ x + 1 ] = temp ; } } } /** * 遍历数组的方法 */ public static void print(int[] arr){ System.out.print("["); for(int x = 0 ; x < arr.length ; x++){ if(x == arr.length - 1){ System.out.println(arr[x] + "]"); }else { System.out.print(arr[x] + ", "); } } }} -------------本文结束感谢您的阅读------------- 打赏 微信支付 支付宝