There are several ways in which bubbling sorting works, some of which are the k+x position compared to the K-position (natural number of x>0), which is exchanged in accordance with the exchange conditions. Some data say that the k+1 position is compared with the K position.
- I just checked the information and summed it up. I think since it's bubbling, it should be that all the elements should be ranked up to the top of each trip . It is impossible to run directly from the bottom to the surface.
- So the right sort of thinking should be: the next two elements are compared to bubble bubble (swap).
According to the above-mentioned authentic principle: the first time the code is drawn should be:
Packagecom.you.test; Public classTest { Public Static voidMain (string[] args) {//TODO auto-generated Method Stub int[] A = {8,1,6,2,5,7,3,4,9}; intTMP = 0;//Buffer for(inti=0;i<a.length;i++){ for(intj=0;j<a.length-1;j++){ if(A[j]>a[j+1]) {//bubble-fit, bubbling onceTMP =A[j]; A[J]= A[j+1]; A[j+1] =tmp; } } //This trip sort of endedPrinta (a); } } Public Static voidPrintaint[] a) { for(inti=0;i<a.length;i++) {System.out.print (" "+A[i]); } System.out.println (""); }}
Run result: and time complexity: n*n
- Solve internal and external cycle times problem. Improvements are as follows:
Packagecom.you.test; Public classTest { Public Static voidMain (string[] args) {//TODO auto-generated Method Stub int[] A = {8,1,6,2,5,7,3,4,9}; intTMP = 0;//Buffer//the large (small) number continues to sink until the bottom, the small (large) number of layers upward. So the tail part is orderly. for(inti=0;i<a.length-1;i++){ for(intj=0;j<a.length-i-1;j++){ if(A[j]>a[j+1]) {//bubble-fit, bubbling onceTMP =A[j]; A[J]= A[j+1]; A[j+1] =tmp; } } //This trip sort of endedPrinta (a); } } Public Static voidPrintaint[] a) { for(inti=0;i<a.length;i++) {System.out.print (" "+A[i]); } System.out.println (""); }}
running Result: the number of internal loops becomes smaller and the external is unchanged.
- Invalid loop is still present, then improved on invalid loop: code:
Packagecom.you.test; Public classTest { Public Static voidMain (string[] args) {//TODO auto-generated Method Stub int[] A = {8,1,6,2,5,7,3,4,9}; intTMP = 0;//Buffer BooleanIs_changed =true;//Bubble identification,//the large (small) number continues to sink until the bottom, the small (large) number of layers upward. So the tail part is orderly. while(is_changed) {is_changed=false; for(intj=0;j<a.length-1;j++){ if(A[j]>a[j+1]) {//bubble-fit, bubbling onceTMP =A[j]; A[J]= A[j+1]; A[j+1] =tmp; Is_changed=true;//There are elements bubbling, } } //This trip sort of endedPrinta (a); } } //Print Public Static voidPrintaint[] a) { for(inti=0;i<a.length;i++) {System.out.print (" "+A[i]); } System.out.println (""); }}
Operation Result:
Here you can complete the bubbling improvements ....
Summary of authentic bubble sorting algorithm