Bubble sort is the most basic sorting algorithm in the sorting algorithm.
The principle is that the adjacent number 22 is compared and exchanged in order from small to large or from large to small
Package Com.neuedu.java; Public classBubblesort { Public Static voidMain (string[] args) {int[] arr=New int[]{0,9,5, $, A,94, About,7}; Bubblesort (arr); for(intI=0; i<arr.length;i++) {System. out. Print (arr[i]+" "); } } /** Bubble Sorting algorithm*/ Public Static voidBubblesort (int[] a) { intCount=0; intLength=a.length; for(intI=
0
; i<length-1; i++){ for(intj=length-2; j>=i;j--){ if(a[j+1]<A[j]) { inttem=a[j+1]; A[j+1]=A[j]; A[J]=tem; } Count++; }} System. out. println ("total number of cycles:"+count); }}
If the array to be sorted is already in order, using the algorithm above will be completely compared again, we can also make improvements, that is, when the array is detected in order to stop the
Optimization of bubble sort
Package Com.neuedu.java; Public classBubblesort { Public Static voidMain (string[] args) {int[] arr=New int[]{0,9,5, $, A,94, About,7}; Bubblesort (arr); for(intI=0; i<arr.length;i++) {System. out. Print (arr[i]+" "); } } /** Optimization of bubble sorting algorithm*/ Public Static voidBubblesort (int[] a) { intCount=0; Record cycle timesintLength=a.length;
Boolean flag=true;//Set a tag to determine if the array is ordered
for (int i=
0
; i<length-1
&&flag
; i++) {//array not ordered, continue to Loop
Flag=false;//initial value is False
for (int j=length-2; j>=i;j--) { if(a[j+1]<a[j]) { int tem=a[j+1]; A[j+1]=a[j]; A[J]=tem;
flag=true; Data exchange, indicating that it is not an ordered array
} count+ +;} } System. out. println (" total number of cycles:"+count);} }
Big talk data structure----bubble sort bubble