首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >同时使用堆排序和快速排序

同时使用堆排序和快速排序
EN

Stack Overflow用户
提问于 2014-12-10 02:43:58
回答 1查看 188关注 0票数 1

我必须同时使用堆排序和快速排序,以便当递归深度超过原始列表大小的2的日志基时,它切换到堆排序实现。

我的堆排序功能:

代码语言:javascript
复制
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

我的快速排序功能:

代码语言:javascript
复制
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,以便它在堆排序和快速排序之间切换:

代码语言:javascript
复制
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有什么问题。不过,我的堆排序和快速排序执行得很好。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-12-10 02:53:28

您可以很好地启动quipSortRec,但是else看起来应该像一个quickSort的副本,现在调用的是递归调用quipSortRec

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27392515

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档