java排序之冒泡排序
代码:
1 package com.cn.algorithm_arithmetic算法; 2 /** 3 * 本程序记录了经典排序算法之冒泡排序 4 * @author Administrator 5 * 6 */ 7 8 public class Bubble_Sort { 9 //冒泡排序优化前 10 public static void bubble_sort(int [] a){ 11 for (int i = 0; i < a.length-1; i++) { 12 for (int j = 0; j < a.length-i-1; j++) { 13 if (a[j+1] < a[j]){ 14 int temp = a[j]; 15 a[j] = a[j+1]; 16 a[j+1] = temp; 17 } 18 } 19 } 20 } 21 22 //冒泡排序优化后 23 public static int[] bubble_sort_optimize(int a[]){ 24 for (int i = 0; i < a.length-1; i++) { 25 boolean exchange = false; 26 for (int j = 0; j < a.length-i-1; j++) { 27 if (a[j+1]<a[j]){ 28 int tmp = a[j]; 29 a[j] = a[j+1]; 30 a[j+1]=tmp; 31 exchange = true; 32 } 33 34 } 35 if (exchange = false){ 36 break; 37 } 38 } 39 return a; 40 } 41 42 public static void main(String[] args) { 43 System.out.println("--------------优化前--------------"); 44 System.out.print("冒泡排序优化前原始数据:"); 45 int a[] = new int[5]; 46 for (int i = 0; i < a.length; i++) { 47 a[i] = (int)(Math.random()*100); 48 System.out.print(a[i]+" "); 49 } 50 bubble_sort(a); 51 System.out.print("\n冒泡排序优化前新数据:"); 52 for (int i = 0; i < a.length; i++) { 53 System.out.print(a[i]+" "); 54 } 55 System.out.println("\n---------------优化后--------------"); 56 //冒泡排序 57 System.out.print("冒泡排序优化后原始数据:"); 58 int a1[] = new int[5]; 59 for (int i = 0; i < a1.length; i++) { 60 a1[i] = (int)(Math.random()*100); 61 System.out.print(a1[i]+" "); 62 } 63 bubble_sort_optimize(a1); 64 System.out.print("\n冒泡排序优化后新数据:"); 65 for (int i = 0; i < a1.length; i++) { 66 System.out.print(a1[i]+" "); 67 } 68 } 69 70 }
冒泡排序的时间复杂度:理想O(n),平均O(n^2),助记口决:外管轮询内管排