原文: http://106.13.73.98/__/117/
挖坑法思路:
- 取一个元素p(第一个元素),使元素p归位;
- 列表被p分成两部分,左边的数一定不大于p,右边的数一定不小于p;
- 递归完成排序。
Python代码示例:
lst = [5, 7, 4, 3, 1, 2, 9, 8]
def quick_sort(d, l, r):
if l < r:
m = partition(d, l, r)
quick_sort(d, l, m - 1)
quick_sort(d, m + 1, r)
def partition(d, l, r):
# 挖坑法,函数执行结束后,左边的数一定不大于p,右边的数一定不小于p
p = d[l]
while l < r:
while l < r and d[r] >= p:
r -= 1
d[l] = d[r]
while l < r and d[l] <= p:
l += 1
d[r] = d[l]
d[l] = p
return l
quick_sort(lst, 0, len(lst) - 1)
《算法导论》中的快速排序:
class QuickSort(object):
__INSTANCE = None
def __new__(cls, *args, **kwargs):
"""单例模式"""
if not cls.__INSTANCE:
cls.__INSTANCE = object.__new__(cls)
return cls.__INSTANCE
def __init__(self, data):
self.__quick_sort(data, 0, len(data) - 1)
def __quick_sort(self, d, l, r):
if l < r:
q = self.__partition(d, l, r)
self.__quick_sort(d, l, q - 1)
self.__quick_sort(d, q + 1, r)
def __partition(self, d, l, r):
x = d[r] # last value
i = l - 1 # last index
for j in range(l, r):
if d[j] <= x:
i += 1
d[i], d[j] = d[j], d[i]
d[i + 1], d[r] = d[r], d[i + 1]
return i + 1
QuickSort(lst)
原文: http://106.13.73.98/__/117/
原文地址:https://www.cnblogs.com/gqy02/p/11326456.html
时间: 2024-10-06 04:55:51