🧮 冒泡排序 (Bubble Sort)
难度 / Difficulty: 简单 (Easy)
分类 / Category: 排序 (Sorting)
时间复杂度 / Time Complexity: O(n²)
空间复杂度 / Space Complexity: O(1)
📖 算法简介 / Introduction
冒泡排序是一种简单的排序算法,通过相邻元素的比较和交换将最大(或最小)的元素逐步冒泡到序列的一端。
Bubble sort is a simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order.
💡 算法原理 / Principle
重复遍历数组,比较相邻元素,大的往后冒泡。优化版本可在提前排好序时停止。
Repeatedly traverse the array, comparing adjacent elements and bubbling the larger one to the end. The optimized version stops early when no swaps are needed.
📝 代码实现 / Implementation
def bubble_sort(arr):
n = len(arr)
for i in range(n):
swapped = False
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
swapped = True
if not swapped:
break
return arr
✨ 示例 / Example
数组 [64, 34, 25, 12, 22, 11] 排序后为 [11, 12, 22, 25, 34, 64]。
Array [64, 34, 25, 12, 22, 11] becomes [11, 12, 22, 25, 34, 64] after sorting.
🎯 适用场景 / Scenarios
教学理解, 小规模数据排序, 检查是否已排序
Educational purposes, Small datasets, Checking if already sorted
🔄 扩展阅读 / Further Reading
- 建议在 LeetCode 或 HackerRank 上刷相关题目
- 尝试自己实现非递归版本
- 对比其他同类型算法的性能差异
| *本文由 AI 自动生成 | Generated by AI* |