冒泡算法的核心思想犹如冒泡一样小的数一轮往上冒,大的数往下沉。(或者相反),所以记不住冒泡的可以想象水的冒泡。
冒泡排序实现:
代码实现:
/**
* 冒泡算法
*/
public class maopao {
public static void main(String[] args) {
int[] array = {45,43,98,23,21,28,56,24,58};
int i = 0;
//外层循环控制比较的次数
while (iarray[j+1]){
int temp=array[j];
array[j]=array[j+1];
array[j+1]=temp;
}
}
i++;
System.out.println(Arrays.toString(array));
}
System.out.println(Arrays.toString(array));
}
}
运算结果:
[43, 45, 23, 21, 28, 56, 24, 58, 98]
[43, 23, 21, 28, 45, 24, 56, 58, 98]
[23, 21, 28, 43, 24, 45, 56, 58, 98]
[21, 23, 28, 24, 43, 45, 56, 58, 98]
[21, 23, 24, 28, 43, 45, 56, 58, 98]
[21, 23, 24, 28, 43, 45, 56, 58, 98]
[21, 23, 24, 28, 43, 45, 56, 58, 98]
[21, 23, 24, 28, 43, 45, 56, 58, 98]
[21, 23, 24, 28, 43, 45, 56, 58, 98]