This commit is contained in:
krahets
2023-03-03 02:46:12 +08:00
parent 122805bdc9
commit cf9d102ed5
24 changed files with 320 additions and 314 deletions
+2 -2
View File
@@ -87,8 +87,8 @@ comments: true
=== "Python"
```python title="bubble_sort.py"
""" 冒泡排序 """
def bubble_sort(nums):
""" 冒泡排序 """
n = len(nums)
# 外循环:待排序元素数量为 n-1, n-2, ..., 1
for i in range(n - 1, 0, -1):
@@ -295,8 +295,8 @@ comments: true
=== "Python"
```python title="bubble_sort.py"
""" 冒泡排序(标志优化) """
def bubble_sort_with_flag(nums):
""" 冒泡排序(标志优化) """
n = len(nums)
# 外循环:待排序元素数量为 n-1, n-2, ..., 1
for i in range(n - 1, 0, -1):
+2 -2
View File
@@ -63,9 +63,9 @@ comments: true
=== "Python"
```python title="insertion_sort.py"
""" 插入排序 """
def insertion_sort(nums):
# 外循环:base = nums[1], nums[2], ..., nums[n-1]
""" 插入排序 """
# 外循环:base = nums[1], nums[2], ..., nums[n-1]
for i in range(1, len(nums)):
base = nums[i]
j = i - 1
+4 -4
View File
@@ -146,10 +146,10 @@ comments: true
=== "Python"
```python title="merge_sort.py"
""" 合并左子数组和右子数组 """
# 左子数组区间 [left, mid]
# 右子数组区间 [mid + 1, right]
def merge(nums, left, mid, right):
""" 合并左子数组和右子数组 """
# 左子数组区间 [left, mid]
# 右子数组区间 [mid + 1, right]
# 初始化辅助数组 借助 copy模块
tmp = nums[left:right + 1]
# 左子数组的起始索引和结束索引
@@ -173,8 +173,8 @@ comments: true
nums[k] = tmp[j]
j += 1
""" 归并排序 """
def merge_sort(nums, left, right):
""" 归并排序 """
# 终止条件
if left >= right:
return # 当子数组长度为 1 时终止递归
+5 -5
View File
@@ -100,8 +100,8 @@ comments: true
=== "Python"
```python title="quick_sort.py"
""" 哨兵划分 """
def partition(self, nums, left, right):
""" 哨兵划分 """
# 以 nums[left] 作为基准数
i, j = left, right
while i < j:
@@ -333,8 +333,8 @@ comments: true
=== "Python"
```python title="quick_sort.py"
""" 快速排序 """
def quick_sort(self, nums, left, right):
""" 快速排序 """
# 子数组长度为 1 时终止递归
if left >= right:
return
@@ -552,8 +552,8 @@ comments: true
=== "Python"
```python title="quick_sort.py"
""" 选取三个元素的中位数 """
def median_three(self, nums, left, mid, right):
""" 选取三个元素的中位数 """
# 此处使用异或运算来简化代码
# 异或规则为 0 ^ 0 = 1 ^ 1 = 0, 0 ^ 1 = 1 ^ 0 = 1
if (nums[left] < nums[mid]) ^ (nums[left] < nums[right]):
@@ -562,8 +562,8 @@ comments: true
return mid
return right
""" 哨兵划分(三数取中值) """
def partition(self, nums, left, right):
""" 哨兵划分(三数取中值) """
# 以 nums[left] 作为基准数
med = self.median_three(nums, left, (left + right) // 2, right)
# 将中位数交换至数组最左端
@@ -845,8 +845,8 @@ comments: true
=== "Python"
```python title="quick_sort.py"
""" 快速排序(尾递归优化) """
def quick_sort(self, nums, left, right):
""" 快速排序(尾递归优化) """
# 子数组长度为 1 时终止
while left < right:
# 哨兵划分操作