1. Basic writing
Import Java. util. arrays; public class testbubble {public static void main (string [] ARGs) {int [] arr = {, 0}; For (Int J = 0; j <arr. length-1; j ++) {// compare several system entries. out. println ("th" + (J + 1) + ""); For (INT I = 0; I <arr. length-1; I ++) {// compare system times per trip. out. print (I + 1) + "times"); If (ARR [I]> arr [I + 1]) {int temp = arr [I]; arr [I] = arr [I + 1]; arr [I + 1] = temp;} system. out. println (arrays. tostring (ARR ));}}}}
Output result:
1st times 1 [1, 4, 7, 3, 0] 2 times [1, 4, 7, 3, 0] 3 times [1, 4, 3, 7, 0] 4 times [1, 4, 3, 0, 7] 2nd times 1 [1, 4, 3, 0, 7] 2 times [1, 3, 4, 0, 7] 3 times [1, 3, 0, 4, 7] 4 times [1, 3, 0, 4, 7] 3rd Times 1 time [1, 3, 0, 4, 7] 2 times [1, 0, 3, 4, 7] 3 times [1, 0, 3, 4, 7] 4 times [1, 0, 3, 4, 7] 4th times 1 [0, 1, 3, 4, 7] 2 times [0, 1, 3, 4, 7] 3 times [0, 1, 3, 4, 7] 4 times [0, 1, 3, 4, 7]
2. Optimized writing, and the first difference is that in the inner loop into I <arr. length-1-j, the original is I <arr. Length-1
Import Java. util. arrays; public class testbubble {public static void main (string [] ARGs) {int [] arr = {, 0}; For (Int J = 0; j <arr. length-1; j ++) {// compare several system entries. out. println ("th" + (J + 1) + ""); For (INT I = 0; I <arr. length-1-j; I ++) {// compare several times per trip, this is critical, arr. the reason for length-1 minus J is that the first number is compared 5 times in the first trip, // The second number is Compared 4 times in the second trip, and the number is decreased in sequence. Therefore, if J // is subtracted, a minimum number system is displayed. out. print (I + 1) + "times"); If (ARR [I]> arr [I + 1]) {int temp = arr [I]; arr [I] = arr [I + 1]; arr [I + 1] = temp;} system. out. println (arrays. tostring (ARR ));}}}}
Output result:
1st times 1 [1, 4, 7, 3, 0] 2 times [1, 4, 7, 3, 0] 3 times [1, 4, 3, 7, 0] 4 times [1, 4, 3, 0, 7] 2nd times 1 [1, 4, 3, 0, 7] 2 times [1, 3, 4, 0, 7] 3 times [1, 3, 0, 4, 7] 3rd Times 1 time [1, 3, 0, 4, 7] 2 times [1, 0, 3, 4, 7] 4th times 1 trip [0, 1, 3, 4, 7]
It can be seen that the number of executions is significantly reduced, and the number of workers remains unchanged, reducing the number of executions per trip.
PS: array. tostring (array) outputs the array content in a certain format and order, which is relatively simple. Of course, you can also use the for loop to output array elements, which is more troublesome.