mirror of
https://github.com/chefyuan/algorithm-base.git
synced 2025-08-10 09:01:58 +00:00
添加了python版本代码
为数据结构和算法文件夹下的代码增加了python语言版本
This commit is contained in:
@@ -22,6 +22,8 @@
|
||||
|
||||
**直接插入排序代码**
|
||||
|
||||
Java Code:
|
||||
|
||||
```java
|
||||
class Solution {
|
||||
public int[] sortArray(int[] nums) {
|
||||
@@ -48,6 +50,31 @@ class Solution {
|
||||
}
|
||||
```
|
||||
|
||||
Python Code:
|
||||
|
||||
```python
|
||||
from typing import List
|
||||
class Solution:
|
||||
def sortArray(self, nums: List[int])->List[int]:
|
||||
# 注意 i 的初始值为 1 ,也就是第二个元素开始
|
||||
for i in range(1, len(nums)):
|
||||
# 待排序的值
|
||||
temp = nums[i]
|
||||
# 需要注意
|
||||
j = i - 1
|
||||
while j >= 0:
|
||||
# 找到合适位置
|
||||
if temp < nums[j]:
|
||||
nums[j + 1] = nums[j]
|
||||
j -= 1
|
||||
continue
|
||||
# 跳出循环
|
||||
break
|
||||
# 插入到合适位置,这也就是我们没有在循环内定义变量的原因
|
||||
nums[j + 1] = temp
|
||||
return nums
|
||||
```
|
||||
|
||||
**直接插入排序时间复杂度分析**
|
||||
|
||||
最好情况时,也就是有序的时候,我们不需要移动元素,每次只需要比较一次即可找到插入位置,那么最好情况时的时间复杂度为O(n)。
|
||||
|
Reference in New Issue
Block a user