pull/21/head
NIngCoder 2 years ago
parent 818fb54efb
commit db9faf98e1

@ -19,19 +19,19 @@ def merge(nums, left, mid, right):
# 初始化辅助数组 借助 copy模块
tmp = nums[left:right + 1]
# 左子数组的起始索引和结束索引
leftStart, leftEnd = left - left, mid - left
left_start, left_end = left - left, mid - left
# 右子数组的起始索引和结束索引
rightStart, rightEnd = mid + 1 - left, right - left
right_start, right_end = mid + 1 - left, right - left
# i, j 分别指向左子数组、右子数组的首元素
i, j = leftStart, rightStart
i, j = left_start, right_start
# 通过覆盖原数组 nums 来合并左子数组和右子数组
for k in range(left, right + 1):
# 若 “左子数组已全部合并完”,则选取右子数组元素,并且 j++
if i > leftEnd:
if i > left_end:
nums[k] = tmp[j]
j += 1
# 否则,若 “右子数组已全部合并完” 或 “左子数组元素 < 右子数组元素”,则选取左子数组元素,并且 i++
elif j > rightEnd or tmp[i] <= tmp[j]:
elif j > right_end or tmp[i] <= tmp[j]:
nums[k] = tmp[i]
i += 1
# 否则,若 “左子数组元素 > 右子数组元素”,则选取右子数组元素,并且 j++
@ -39,14 +39,13 @@ def merge(nums, left, mid, right):
nums[k] = tmp[j]
j += 1
""" 归并排序 """
def merge_sort(nums, left, right):
# 终止条件
if left >= right:
return # 当子数组长度为 1 时终止递归
# 划分阶段
mid = left + right >> 1 # 计算中点
mid = (left + right) // 2 # 计算中点
merge_sort(nums, left, mid) # 递归左子数组
merge_sort(nums, mid + 1, right) # 递归右子数组
# 合并阶段

@ -11,7 +11,7 @@ import os.path as osp
sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__))))
""" 快速排序类 """
class quick_sort(object):
class QuickSort(object):
""" 哨兵划分 """
def partition(self, nums, left, right):
# 以 nums[left] 作为基准数
@ -40,7 +40,7 @@ class quick_sort(object):
""" 快速排序类(中位基准数优化)"""
class quick_sort_median():
class QuickSortMedian():
""" 选取三个元素的中位数 """
def median_three(self, nums, left, mid, right):
@ -83,7 +83,7 @@ class quick_sort_median():
""" 快速排序类(尾递归优化) """
class quick_sort_tail_call():
class QuickSortTailCall():
""" 哨兵划分 """
def partition(self, nums, left, right):
# 以 nums[left] 作为基准数
@ -117,15 +117,15 @@ class quick_sort_tail_call():
if __name__ == '__main__':
# 快速排序
nums = [4, 1, 3, 1, 5, 2]
quick_sort().quick_sort(nums, 0, len(nums) - 1)
QuickSort().quick_sort(nums, 0, len(nums) - 1)
print("快速排序完成后 nums = ", nums)
# 快速排序(中位基准数优化)
nums1 = [4, 1, 3, 1, 5, 2]
quick_sort_median().quick_sort(nums1, 0, len(nums1) - 1)
QuickSortMedian().quick_sort(nums1, 0, len(nums1) - 1)
print("快速排序(中位基准数优化)完成后 nums = ", nums)
# 快速排序(尾递归优化)
nums2 = [4, 1, 3, 1, 5, 2]
quick_sort_tail_call().quick_sort(nums, 0, len(nums2) - 1)
QuickSortTailCall().quick_sort(nums, 0, len(nums2) - 1)
print("快速排序(尾递归优化)完成后 nums = ", nums)

Loading…
Cancel
Save