1. Fix the import error.
2. Some codes fine tuning.
This commit is contained in:
@@ -44,6 +44,22 @@ comments: true
|
||||
}
|
||||
```
|
||||
|
||||
=== "Python"
|
||||
|
||||
```python
|
||||
""" 插入排序 """
|
||||
def insertion_sort(nums):
|
||||
# 外循环:base = nums[1], nums[2], ..., nums[n-1]
|
||||
for i in range(1, len(nums)):
|
||||
base = nums[i]
|
||||
j = i - 1
|
||||
# 内循环:将 base 插入到左边的正确位置
|
||||
while j >= 0 and nums[j] > base:
|
||||
nums[j + 1] = nums[j] # 1. 将 nums[j] 向右移动一位
|
||||
j -= 1
|
||||
nums[j + 1] = base # 2. 将 base 赋值到正确位置
|
||||
```
|
||||
|
||||
## 算法特性
|
||||
|
||||
**时间复杂度 $O(n^2)$ :** 最差情况下,各轮插入操作循环 $n - 1$ , $n-2$ , $\cdots$ , $2$ , $1$ 次,求和为 $\frac{(n - 1) n}{2}$ ,使用 $O(n^2)$ 时间。
|
||||
|
Reference in New Issue
Block a user