Bubble sort and its optimization I. Principle and optimization principle 1. Explanation of principle
Bubble sort is: the first number is compared with the second number, if the condition position is not changed, then the second number is compared with the third number. If the condition is not satisfied, the position is replaced, the second number is compared with the third number, and so on, the number of trips equals the number of comparisons minus one.
2. Bubble Sorting Principle diagram: (Take the 98765 sequence as an example, the results of the order from small to large)
3. Bubble Sort Optimization
Optimized: Reduce one cycle at a time (i.e. the red part does not need to be compared)
4. Bubble Sort Final version
Final version: Reduce one cycle per trip (strikethrough does not need to be executed)
Two. Implementation code 1. Bubble Sort Implementation main code
Public Static voidMain (string[] args) {int[]arr={9,8,7,6,5}; intlen=arr.length; for(inti=0;i<len-1;i++) { for(intj=0;j<len-1;j++) { if(arr[j]>arr[j+1]){ inttemp=Arr[j]; ARR[J]=arr[j+1]; Arr[j+1]=temp; }}} System.out.println (Arrays.tostring (arr)); }
Bubble Sort Implementation code
2. Bubble Sort Optimization Code
Public Static voidMain (string[] args) {int[]arr={9,8,7,6,5}; intlen=arr.length; for(inti=0;i<len-1-i;i++) { for(intj=0;j<len-1;j++) { if(arr[j]>arr[j+1]){ inttemp=Arr[j]; ARR[J]=arr[j+1]; Arr[j+1]=temp; }}} System.out.println (Arrays.tostring (arr)); }
Bubble Sort Optimization code
3. Bubble Sort Final Code
Public Static voidMain (string[] args) {int[]arr={9,8,7,6,5}; intlen=arr.length; for(inti=0;i<len-1;i++) {System.out.println ("First" + (i+1) + "Trip"); //Increase judgment bit Booleanflag=true; for(intj=0;j<len-1-i;j++) {System.out.println ("First" + (j+1) + "secondary"); if(arr[j]>arr[j+1]){ inttemp=Arr[j]; ARR[J]=arr[j+1]; Arr[j+1]=temp; Flag=false; } System.out.println (Arrays.tostring (arr)); } //If the above does not perform a direct exit if(flag) { Break; }} System.out.println (Arrays.tostring (arr)); }
Bubble Sort Final version
Three. Precautions 1. Think more
Java_ Bubble Sort _ principle and optimization