🧑💻 算法学习 · Bubble Sort
冒泡排序 (Bubble Sort)
概述
难度:简单 (Easy)
分类:Sorting / 排序
冒泡排序是一种简单的排序算法,通过相邻元素的比较和交换将最大(或最小)的元素逐步冒泡到序列的一端。
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.
算法原理
中文:重复遍历数组,比较相邻元素,大的往后冒泡。优化版本可在提前排好序时停止。
English: 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.
复杂度分析
| 类型 | 复杂度 |
|---|---|
| 时间复杂度 | O(n²) |
| 空间复杂度 | O(1) |
代码实现
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
每日练习
- 完成算法实现
- 分析算法复杂度
- 思考:算法的适用场景和局限性
相关阅读:算法专栏
💡 学习建议:算法学习重在理解思想,多写多练是关键。 💡 Learning tip: Algorithm learning is about understanding the core idea. Practice makes perfect.