实现思路:
1、通过比较相邻的两个元素,如果第一个数比第二个数大,那么就交换两者的位置
2、第一趟之后,最后一个元素就是整个数组中最大的数。
3、重复步骤一,每一趟最后一个元素在下一趟不参与比较。
4、重复步骤3,直到没有需要比较的数字为止。
java算法实现:
1、普通版冒泡排序:
1 public static void bubbleSort(int[] arr){ 2 for(int i=0;i<arr.length-1;i++){ 3 for(int j=0;j<arr.length-1-i;j++){ 4 if(arr[j]>arr[j+1]){ 5 int temp = arr[j]; 6 arr[j] = arr[j+1]; 7 arr[j+1] = temp; 8 } 9 } 10 } 11 }
普通版有个缺陷:即使是一个已经排好序的数组,它依然会去进行一趟趟比较。影响效率。如下所示:
1 public class Test { 2 public static void main(String[] args) { 3 int[] a = {1,2,3,4,5,6,7}; 4 bubbleSort(a); 5 for(int b:a){ 6 System.out.print(b+" "); 7 } 8 } 9 10 public static void bubbleSort(int[] arr){ 11 //统计比较次数 12 int count1 = 0; 13 //统计比较趟数 14 int count2 = 0; 15 for(int i=0;i<arr.length-1;i++){ 16 for(int j=0;j<arr.length-1-i;j++){ 17 if(arr[j]>arr[j+1]){ 18 int temp = arr[j]; 19 arr[j] = arr[j+1]; 20 arr[j+1] = temp; 21 } 22 count1++; 23 } 24 count2++; 25 } 26 System.out.println("比较次数为:"+count1); 27 System.out.println("比较趟数为:"+count2); 28 } 29 }
输出结果为:比较次数为:21
比较趟数为:6
1 2 3 4 5 6 7
2、优化版冒泡排序:
1 public class Test { 2 public static void main(String[] args) { 3 int[] a = {1,2,3,4,5,6,7}; 4 bubbleSort(a); 5 for(int b:a){ 6 System.out.print(b+" "); 7 } 8 } 9 10 public static void bubbleSort(int[] arr){ 11 //统计比较次数 12 int count1 = 0; 13 //统计比较趟数 14 int count2 = 0; 15 //设置一个标记 16 boolean flag ; 17 for(int i=0;i<arr.length-1;i++){ 18 flag = true; 19 for(int j=0;j<arr.length-1-i;j++){ 20 if(arr[j]>arr[j+1]){ 21 //如果发生了交换,说明没有排好序,那么标志为false。 22 flag = false; 23 int temp = arr[j]; 24 arr[j] = arr[j+1]; 25 arr[j+1] = temp; 26 } 27 count1++; 28 } 29 count2++; 30 //只要有一趟没有发生交换,说明已经排好序,那么标志为true,并且退出循环。 31 if(flag){ 32 break; 33 } 34 } 35 System.out.println("比较次数为:"+count1); 36 System.out.println("比较趟数为:"+count2); 37 } 38 } 39 40 输出结果为:比较次数为:6 41 比较趟数为:1 42 1 2 3 4 5 6 7
大大减少了排序趟数,提高了效率。