添加了python版本代码

为数据结构和算法文件夹下的代码增加了python语言版本
This commit is contained in:
goodyong
2021-07-05 22:25:41 +08:00
parent a503e97f11
commit 4e661354d4
16 changed files with 1088 additions and 83 deletions

View File

@@ -80,6 +80,8 @@
我们来看一下这段代码
Java Code:
```java
class Solution {
public int[] sortArray(int[] nums) {
@@ -102,6 +104,25 @@ class Solution {
}
```
Python Code:
```python
from typing import List
class Solution:
def sortArray(self, nums: List[int])->List[int]:
leng = len(nums)
for i in range(0, leng):
for j in range(i + 1, leng):
if nums[i] > nums[j]:
self.swap(nums, i, j)
return nums
def swap(self, nums: List[int], i: int, j: int):
temp = nums[i]
nums[i] = nums[j]
nums[j] = temp
```
我们来思考一下上面的代码每次让关键字 nums[i] nums[j] 进行比较如果 nums[i] > nums[j] 时则进行交换这样 nums[0] 在经过一次循环后一定为最小值那么这段代码是冒泡排序吗
显然不是我们冒泡排序的思想是两两比较**相邻记录**的关键字注意里面有相邻记录所以这段代码不是我们的冒泡排序下面我们用动图来模拟一下冒泡排序的执行过程看完之后一定可以写出正宗的冒泡排序
@@ -143,6 +164,8 @@ class Solution {
我们来对冒泡排序进行改进
Java Code:
```java
class Solution {
public int[] sortArray(int[] nums) {
@@ -172,6 +195,32 @@ class Solution {
}
```
Python Code:
```python
from typing import List
class Solution:
def sortArray(self, nums: List[int])->List[int]:
leng = len(nums)
# 标志位
flag = True
for i in range(0, leng):
if not flag:
break
flag = False
for j in range(0, leng - i - 1):
if nums[j] > nums[j + 1]:
self.swap(nums, j, j + 1)
# 发生交换则变为true下次继续判断
flag = True
return nums
def swap(self, nums: List[int], i: int, j: int):
temp = nums[i]
nums[i] = nums[j]
nums[j] = temp
```
这样我们就避免掉了已经有序的情况下无意义的循环判断
**冒泡排序时间复杂度分析**