java bubble sort simple example
- 2020-05-30 20:17:05
- OfStack
Without further ado, look at the code:
// Bubble sort, which loops the comparison back and forth from the front of the array
public static void sort1(int[] aa){
int size=aa.length;
int temp;
// Circular array
for(int i=0;i<size;i++){
//aa[i] Respectively with i All the Numbers after bits are compared and swapped, aa[i] Become the minimum
for(int j=i+1;j<size;j++){
if(aa[i]>aa[j]){
temp=aa[i];
aa[i]=aa[j];
aa[j]=temp;
}
}
}
for(int i=0;i<aa.length;i++){
System.out.println(aa[i]);
}
}
The second for loop compares the aa[i] of the first for loop with the other Numbers starting from i+1 bit, respectively. If it is smaller than aa[i], then swap aa[i] and aa[j]. Through the layer 2 for loop, aa[i] will be the minimum of all Numbers starting from i+1 bit. By analogy, the minimum values of the remaining digits in the larger digits are obtained by exchanging them. This gives you a small to large order of the array.
// Bubble sort, which loops through the back of the array
public static void sort2(int[] aa){
int size=aa.length;
int temp;
// Circular array
for(int i=0;i<size;i++){
//aa[i] Respectively with i All the Numbers after bits are compared and swapped, aa[i] Become the minimum
for(int j=size-1;j>i;j--){
if(aa[i]>aa[j]){
temp=aa[i];
aa[i]=aa[j];
aa[j]=temp;
}
}
}
for(int i=0;i<aa.length;i++){
System.out.println(aa[i]);
}
}