"Basic Ideas"
Suppose the array is int[] A = {49, 38, 65, 97, 76, 13, 27}, and the number of array elements is 7.
The 1th round comparison: first a[0] and a[1] comparison, greater than the first exchange, and then compare a[0] and a[2] ... The last is a[0] compared to a[6]. Compare 6 times in total. (at this point a[0] is the smallest value in the array)
The 2nd round comparison: first a[1] and a[2] comparison, greater than the first exchange, and then compare a[1] and a[3] ... The last is a[1] compared to a[6]. Compare 5 times in total.
The 3rd round comparison: first a[2] and a[3] comparison, greater than the first exchange, and then compare a[2] and a[4] ... The last is a[2] compared to a[6]. Compare 4 times in total.
The 4th round comparison: first a[3] and a[4] comparison, greater than the first exchange, and then compare a[3] and a[5] ... The last is a[3] compared to a[6]. Compare 3 times in total.
The 5th round comparison: first a[4] and a[5] comparison, greater than the first exchange, and then compare a[4] and a[6]. Compare 2 times in total.
The 6th round comparison: only use a[5] and a[6], greater than the first exchange. Compare 1 times in total.
"Code Implementation"
Public classTest { Public Static voidMain (string[] args) {//given array int[] A = {49, 38, 65, 97, 76, 13, 27 }; //the outer for loop control compares the first few rounds for(inti = 0; i < a.length-1; i++) { //The inner for loop controls the number of comparisons per round, a[j] is the right-to-do element for(intj = i + 1; J < A.length; J + +) { //determine if left is greater than right if(A[i] >A[j]) { //Exchanging Data inttemp; Temp=A[i]; A[i]=A[j]; A[J]=temp; } } } //Print sorted Array for(inti = 0; i < a.length; i++) { if(I! = a.length-1) {System.out.print (A[i]+ ", "); } Else{System.out.print (a[i]); } } }}
Common sort methods in Java-select sort (Ascending)