如何在我的快速排序算法中获得输出

时间:2017-02-25 19:08:36

标签: python algorithm quicksort

我正在尝试在我的快速排序算法中实现递归和列表理解。但我无法看到任何输出。我可以请求帮助,我应该添加哪些行来查看输出。我的逻辑似乎是正确的,并且赞赏反馈。

def partition_list(A):
    n = len(A)
    m = A[n - 1]
    #print m
    A_left = [x for x in A if x <= m]
    A_right = [x for x in A if x > m]
    #if len(A_left) >= 2:
    #    return partition_list(A_left)

    Anew = A_left + A_right
    ind = Anew.index(m)
    return Anew,ind

在以下函数中调用此函数partition_list。

def quick_sort_helper(A):
    if len(A) > 1:
        Anew,m1 = partition_list(A)
        print Anew
        Aleft = Anew[0:m1]
        Aright = Anew[m1 + 1:len(A)]
        quick_sort_helper(Aleft)
        print Aleft
        quick_sort_helper(Aright)
    else:
        return A  

1 个答案:

答案 0 :(得分:0)

Quicksort排序到位。这意味着您必须确保在分区例程找到所选枢轴的最终排序位置时,您可以修改(如果需要)列表到位。分区例程对快速排序至关重要。我看到你使用像 list composition 这样的Python构造,但是这样做,你似乎忘记了quicksort的工作原理。 对于初学者来说 可以要求额外的空间,但是您应该真正编写用于分区给定列表的分区例程

您的递归quick_sort_helper()函数也令人困惑。在非递归的情况下,它返回一个数组,而在递归的情况下,它返回任何内容。 Python(即所谓的)松散类型的语言,并不能阻止你这样做。

我已经尝试纠正代码中的这些缺陷,同时保持您的选择基本上完好无损并且似乎有效。当列表具有重复元素并且留作练习时,它不起作用: - )。

#!/usr/bin/env python


def partition_list(A, loIn, hiEx):
    """
    Partitions the given list between given indexes such that the pivot is in its final sorted location.
    Note: uses additional space.
    :param A: the list of integers
    :param loIn: low index, inclusive
    :param hiEx: high index, exclusive
    :return: index pi of pivot =  (A[hiEx- 1]) in the sorted sequence, thus after the function returns, A[pi] = pivot and loIn <= pi < hiEx
    """
    # print "partition call: loIn = %d, hiEx = %d" % (loIn, hiEx)
    n = hiEx - loIn
    pivot = A[hiEx - 1]  # pivot is fixed, last element of the given array
    # print "pivot: %d" % pivot
    slice = A[loIn:hiEx]
    A_left = [x for x in slice if x <= pivot]
    A_right = [x for x in slice if x > pivot]
    Anew = A_left + A_right
    # print Anew
    # copy it back, defeating the purpose of quicksort
    for i in xrange(n):
        A[loIn + i] = Anew[i]
    index = A.index(pivot, loIn, hiEx)
    # print "partition index: %d, element: %d" % (index, A[index])
    return index


def quick_sort_helper(A, loIn, hiEx):
    """
    Implements quicksort recursively. Call this as: quick_sort_helper(a, 0, len(a))
    :param A: the list to sort
    :param loIn: low index, inclusive
    :param hiEx: high index, exclusive
    :return: nothing, sorts list in place.
    """
    if hiEx - loIn > 1:
        m1 = partition_list(A, loIn, hiEx) # A[m1] is in its final sorted position
        quick_sort_helper(A, loIn, m1)
        quick_sort_helper(A, m1 + 1, hiEx)

a = [43, 2, 52, 23, 1, 0, 10, 7, 3]
quick_sort_helper(a, 0, len(a))
print "sorted: ", a # prints: sorted:  [0, 1, 2, 3, 7, 10, 23, 43, 52]