Post the code first (sorted from small to large):
public class BubbleSort { public static void main(String args[]){ double[] a={0,1,5,9,10,2,4,6,3,7,8,-3,0.4,-2.5}; for (int i=0;i<a.length-1;i++){ //Outer loop controls the number of sorting trips for (int j=0;j<a.length-i-1;j++){ //Inner loop controls how many times each trip is sorted if (a[j]>a[j+1]){ //Two numerical values are judged double num=a[j]; a[j]=a[j+1]; //Swap the large value to the back a[j+1]=num; //Swap the small value to the back} } } for(double k:a){ //Foreach loop output System.out.println(k); }// for (int k=0;k<a.length;k++){ // Ordinary for loop// System.out.println(a[k]); // } } }Note: If you need to arrange from large to small, just modify the larger than the symbol of the if statement.
Annotation: a.length-1 and j<a.length-i-1
For example: To sort the array: int[] arr={6,3,8,2,9,1}; (Note source: //www.VeVB.COM/article/68204.htm)
First order: (i)
First sort: 6 and 3 compare, 6 is greater than 3, swap position: 3 6 8 2 9 1
Second sort: 6 and 8 compare, 6 is less than 8, no exchange position: 3 6 8 2 9 1
The third order: 8 and 2 compare, 8 is greater than 2, swap position: 3 6 2 8 9 1
Fourth order: 8 and 9 compare, 8 is less than 9, no exchange position: 3 6 2 8 9 1
Fifth order: 9 and 1 compare: 9 is greater than 1, swap position: 3 6 2 8 1 9
A total of 5 (j) comparisons were conducted on the first trip, sorting results: 3 6 2 8 1 9
Second order: (i)
First sorting: 3 and 6 compare, 3 is less than 6, no swap position: 3 6 2 8 1 9
Second sort: 6 and 2 compare, 6 is greater than 2, swap position: 3 2 6 8 1 9
The third order: 6 and 8 compare, 6 is greater than 8, no exchange position: 3 2 6 8 1 9
Fourth order: 8 and 1 compare, 8 is greater than 1, swap position: 3 2 6 1 8 9
The second trip was compared in total 4 (j) times, sorting results: 3 2 6 1 8 9
The third order: (i)
First sort: 3 and 2 compare, 3 is greater than 2, swap position: 2 3 6 1 8 9
Second sort: 3 and 6 compare, 3 is less than 6, no swap position: 2 3 6 1 8 9
The third order: 6 and 1 compare, 6 is greater than 1, swap position: 2 3 1 6 8 9
The second trip was compared in total 3 (j) times, sorting results: 2 3 1 6 8 9
Fourth order: (i)
First sorting: 2 and 3 compare, 2 is less than 3, no swap position: 2 3 1 6 8 9
Second sort: 3 and 1 compare, 3 is greater than 1, swap position: 2 1 3 6 8 9
The second trip was compared in total 2 (j) times, sorting results: 2 1 3 6 8 9
The fifth order: (i)
First sorting: 2 and 1 compare, 2 is greater than 1, swap position: 1 2 3 6 8 9
The second trip was compared in total 1 (j) times, sorting result: 1 2 3 6 8 9
Final result: 1 2 3 6 8 9