我必须同时使用堆排序和快速排序,以便当递归深度超过原始列表大小的2的日志基数时,它会切换到堆排序实现。
我的堆排序功能:
import heapq
def heapSort(lst):
"""
heapSort(List(Orderable)) -> List(Ordered)
performs a heapsort on 'lst' returning a new sorted list
Postcondition: the argument lst is not modified
"""
heap = []
for item in lst:
heapq.heappush(heap, item)
sortedlist = []
while len(heap) > 0:
sortedlist.append(heapq.heappop(heap))
return sortedlist
我的快速排序功能:
def medianOf3(lst):
"""
From a lst of unordered data, find and return the the median value from
the first, middle and last values.
"""
a,b,c = lst[0], lst[len(lst)//2], lst[-1]
return min(min(max(a,b), max(b,c)), max(a,c))
def quickSort(lst):
"""
quickSort: List(lst) -> List(result)
Where the return 'result' is a totally ordered 'lst'.
It uses the median-of-3 to select the pivot
e.g. quickSort([1,8,5,3,4]) == [1,3,4,5,8]
"""
if lst == []:
return []
else:
pivot = medianOf3(lst)
less, same, more = partition(pivot, lst)
return quickSort(less) + same + quickSort(more)
def partition( pivot, lst ):
"""
partition: pivot (element in lst) * List(lst) ->
tuple(List(less), List(same, List(more))).
Where:
List(Less) has values less than the pivot
List(same) has pivot value/s, and
List(more) has values greater than the pivot
e.g. partition(5, [11,4,7,2,5,9,3]) == [4,2,3], [5], [11,7,9]
"""
less, same, more = list(), list(), list()
for val in lst:
if val < pivot:
less.append(val)
elif val > pivot:
more.append(val)
else:
same.append(val)
return less, same, more
现在我尝试实现quipSort,以便在堆排序和快速排序之间切换:
def quipSortRec(lst, limit):
"""
A non in-place, depth limited quickSort, using median-of-3 pivot.
Once the limit drops to 0, it uses heapSort instead.
"""
if limit <= 0:
heapSort(lst)
else:
quickSort(lst)
quipSortRec(lst, limit -1)
return lst
def quipSort(lst):
"""
The main routine called to do the sort. It should call the
recursive routine with the correct values in order to perform
the sort
"""
l = math.log2(len(lst))
return quipSortRec(lst, l)
根本没有排序,我有点迷失了我的quipSort的错误。我的堆排序和快速排序表现不错。
答案 0 :(得分:1)
您可以quipSortRec
开始,但else
应该看起来像quickSort
的副本,其中递归调用现在调用quipSortRec
。