- 算法思想
- 排序过程
- 代码实现
- 测试结果
1.冒泡排序算法思想:
冒泡排序对数组相邻元素进行比较,发现逆序则交换。每轮结束后都会将该轮排序元素中最大值排到该轮的最后一位,最终实现整个数组的有序。
2.排序过程:
原始数组:90, 51, 42, 95, 21, 12, 10
第1轮后结果:[51, 42, 90, 21, 12, 10, 95]
第2轮后结果:[42, 51, 21, 12, 10, 90, 95]
第3轮后结果:[42, 21, 12, 10, 51, 90, 95]
第4轮后结果:[21, 12, 10, 42, 51, 90, 95]
第5轮后结果:[12, 10, 21, 42, 51, 90, 95]
第6轮后结果:[10, 12, 21, 42, 51, 90, 95]
3.代码实现:
//冒泡排序
public class BubbleSort {
//测试冒泡排序
public static void main(String[] args) {
int[] array = {90, 51, 42, 95, 21, 12, 10};
bubbleSortFunction(array);
System.out.println(Arrays.toString(array));
}
//冒泡排序实现方法
public static void bubbleSortFunction(int[] array) {
// 轮数
for (int i = 0; i < array.length - 1; i++) {
//每轮中,相邻元素比较,最后将最大值放在本轮元素的最后一位
for (int j = 0; j < array.length - 1 - i; j++) {
//swap 交换相邻的逆序元素
if (array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
}
4.测试结果:
4.1 每轮执行结果:
4.2 最终结果:



