Bubble Sort
Idea
Bubble Sort repeatedly compares adjacent elements and “bubbles” the larger (or smaller) one toward the end, pass by pass, until fully sorted.
冒泡排序演示
4321
Algorithm
- Scan adjacent pairs; swap if out of order.
- Each pass bubbles the max (or min) of the unsorted part to the end.
- Repeat for passes until sorted.
Pseudo-code:
for i = 0 to n-2:
for j = 0 to n-2-i:
if A[j] > A[j+1]:
swap(A[j], A[j+1])
Complexity
- Best: (already sorted, with early-exit optimization)
- Worst/avg:
- Space:
- Stability: stable
Exercises
Exercise 1
Sort with bubble sort; show each pass.
参考答案
思路:每趟把最大元素“冒泡”到末尾。
步骤:
- 初始:[4, 3, 2, 1]
- 第 1 趟:[3, 2, 1, 4]
- 第 2 趟:[2, 1, 3, 4]
- 第 3 趟:[1, 2, 3, 4]
答案:如上,每一趟后最大元素归位。
Exercise 2
What are the time and space complexities of bubble sort?
参考答案
思路:复杂度与空间。
步骤:
- 时间复杂度
- 空间复杂度
答案:时间 ,空间 。