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