Code:
1 Packagecom.cn.algorithm_arithmetic algorithm;2 /**3 * This program records the bubble sort of the classical sorting algorithm4 * @authorAdministrator5 *6 */7 8 Public classBubble_sort {9 //bubble sort before optimizationTen Public Static voidBubble_sort (int[] a) { One for(inti = 0; i < a.length-1; i++) { A for(intj = 0; J < A.length-i-1; J + +) { - if(A[j+1] <A[j]) { - inttemp =A[j]; theA[J] = a[j+1]; -A[J+1] =temp; - } - } + } - } + A //after bubble sort optimization at Public Static int[] Bubble_sort_optimize (inta[]) { - for(inti = 0; i < a.length-1; i++) { - BooleanExchange =false; - for(intj = 0; J < A.length-i-1; J + +) { - if(a[j+1]<A[j]) { - intTMP =A[j]; inA[J] = a[j+1]; -a[j+1]=tmp; toExchange =true; + } - the } * if(Exchange =false){ $ Break;Panax Notoginseng } - } the returnA; + } A the Public Static voidMain (string[] args) { +System.out.println ("--------------before--------------optimization"); -System.out.print ("bubble sort optimization before raw data:"); $ intA[] =New int[5]; $ for(inti = 0; i < a.length; i++) { -A[i] = (int) (Math.random () *100); -System.out.print (a[i]+ ""); the } - Bubble_sort (a);WuyiSystem.out.print ("\ n bubble sort optimization before new data:"); the for(inti = 0; i < a.length; i++) { -System.out.print (a[i]+ ""); Wu } -System.out.println ("\ n---------------Optimized--------------"); About //Bubble Sort $System.out.print ("bubble sort optimized after raw data:"); - intA1[] =New int[5]; - for(inti = 0; i < a1.length; i++) { -A1[i] = (int) (Math.random () *100); ASystem.out.print (a1[i]+ ""); + } the Bubble_sort_optimize (A1); -System.out.print ("\ n bubble sort optimized after new data:"); $ for(inti = 0; i < a1.length; i++) { theSystem.out.print (a1[i]+ ""); the } the } the -}
Time complexity of bubble sort: ideal O (n), average O (n^2), mnemonic: outer tube polling inner pipe row
Java Sort Bubble Sort