【发布时间】:2014-12-10 10:53:28
【问题描述】:
我必须同时使用堆排序和快速排序,以便在递归深度超过原始列表大小的 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 出了什么问题。不过,我的堆排序和快速排序表现良好。
【问题讨论】:
-
课外:堆排序 + 快速排序不应该是“Heck 排序”或“Quap 排序”
-
请比“它不工作”更具体:它应该做什么以及它在做什么?
标签: python python-3.x