核心思想
冒泡排序是通过相邻元素的连续比较和交换,使得较大的元素逐渐"浮"到数组的末尾,如同水中气泡上浮的过程
特点:
- 每轮遍历将最大的未排序元素移动到正确位置
- 稳定排序:相等元素的相对位置保持不变
- 原地排序:不需要额外存储空间
复杂度
情况 | 时间复杂度 | 空间复杂度 |
---|---|---|
最好情况 | O(n) | O(1) |
最坏情况 | O(n²) | O(1) |
平均情况 | O(n²) | O(1) |
优缺点
优点:
- 实现简单,代码易读
- 不需要额外内存空间
- 对部分有序数组效率较高(通过优化)
缺点:
- 时间复杂度较高,不适合大数据量
- 元素需要频繁交换,效率低于其他O(n²)算法(如选择排序)
适用场景:
- 小规模数据排序(n ≤ 1000)
- 数据基本有序的情况
- 日常基本很少使用
代码实现(Java)
java
public class BubbleSortDemo {
public static void bubbleSort(int[] arr) {
int n = arr.length;
//外层循环控制排序轮数
for (int i = 0; i < n - 1; i++) {
//内层循环控制相邻元素比较
for (int j = 0; j < n - i - 1; j++) {
//升序排列的交换逻辑
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
public static void main(String[] args) {
int[] data = {5, 3, 8, 4, 2};
System.out.println("排序前: " + Arrays.toString(data));
bubbleSort(data);
System.out.println("排序后: " + Arrays.toString(data));
}
}
过程示例
初始: 5 3 8 4 2
第1轮:3 5 4 2 [8]
第2轮:3 4 2 [5 8]
第3轮:3 2 [4 5 8]
第4轮:2 [3 4 5 8]