mirror of
https://github.com/chefyuan/algorithm-base.git
synced 2025-08-09 16:42:09 +00:00
添加了python版本代码
为数据结构和算法文件夹下的代码增加了python语言版本
This commit is contained in:
@@ -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
|
||||
```
|
||||
|
||||
这样我们就避免掉了已经有序的情况下无意义的循环判断。
|
||||
|
||||
**冒泡排序时间复杂度分析**
|
||||
|
Reference in New Issue
Block a user