冒泡排序
具体的执行步骤请详细看注释!!!
package com.yongjar.test;
/**
* @author yongjar
* @date 2021/2/26
*
* 冒泡排序
*/
public class BubbleSort {
public static void bubbleSort(int [] a) {
int temp;
// i=1 i<3 true
// -*! i++ = 2; i<3 true
// i++=3
for (int i = 1; i < a.length; i++) {
// j=0; j<3-1 true
// j++=1; j<3-1 true
// -*! j++=2; j<2 false 返回上一个for -*!
// j=0; j<3-2 true
//j=0 j<1 true
for (int j = 0; j <a.length-i ; j++) {
// a[0] 25 > a[0+1] 29 false ,返回执行for循环
//a[1](29) > a[1+1](21) true
//a[0](25) > a[0+1](21) true
if (a[j] > a[j+1]) {
// temp = a[1](29)
//temp = a[0](25)
temp = a[j];
//a[1] = a[2](21)
//a[0] = a[1](21)
a[j] = a[j+1];
//a[2] = temp(29), 返回继续执行for循环-*!
//a[1] = temp(25)
a[j+1] = temp;
}
}
}
}
public static void main(String[] args) {
int [] shuzu = new int[3];
shuzu[0] = 25;
shuzu[1] = 29;
shuzu[2] = 21;
System.out.println ("排序前的数组为:\n");
for (int j = 0; j < 3; j++) {
System.out.print (shuzu[j] + " ");
}
System.out.println ();
bubbleSort (shuzu);
System.out.print ("排序后的数组为:\n");
for (int j = 0; j < 3; j++) {
System.out.print(shuzu[j] + " ");
}
System.out.println ();
}
}