-1

我刚开始学习python。我在尝试在我的程序中实施快速排序时收到错误消息。类型错误:recQuickSort() 缺少 1 个必需的位置参数:“最后一个”。就个人而言,我认为它没有什么问题,因为我是从学校的讲座中获得的。我面临的唯一问题是如何实现它来对字典进行排序。我该如何调用该函数?

下面是我的代码:

# Quick Sort

# Sorts an array or list using the recursive quick sort algorithm
def quickSort(theSeq):
    n = len(theSeq)
    recQuickSort(theSeq, 0, n - 1)


# The recursive "in-place" implementation
def recQuickSort(theSeq, first, last):
    # Check the base case (range is trivially sorted)
    if first >= last:
        return
    else:
        # Partition the sequence and obtain the pivot position
        pos = partitionSeq(theSeq, first, last)
        # Repeat the process on the two subsequences
        recQuickSort(theSeq, first, pos - 1)
        recQuickSort(theSeq, pos + 1, last)

# Partitions the subsequence using the first key as the pivot
def partitionSeq(theSeq, first, last):
    # Save a copy of the pivot value.
    pivot = theSeq[first] # first element of range is pivot
    # Find the pivot position and move the elements around the pivot
    left = first + 1 # will scan rightward
    right = last # will scan leftward
    while left <= right:
    # Scan until reaches value equal or larger than pivot (or right marker)
        while left <= right and theSeq[left] < pivot:
            left += 1
    # Scan until reaches value equal or smaller than pivot (or left marker)
        while left <= right and theSeq[right] > pivot:
            right -= 1
        # Scans did not strictly cross
        if left <= right:
        # swap values
            theSeq[left], theSeq[right] = theSeq[right], theSeq[left]
        # Shrink range (Recursion: Progress towards base case)
            left += 1
            right -= 1
    # Put the pivot in the proper position (marked by the right index)
    theSeq[first], theSeq[right] = theSeq[right], pivot
    # Return the index position of the pivot value.
    return right
4

1 回答 1

0

我复制粘贴了您的代码,它工作正常(此处为 Python 2.7.16)。

这是有关如何调用函数的示例:

a = [3,2,1]
quickSort(a)
# [1, 2, 3]

b = [10,9,8,7,1,2,3,4,5]
quickSort(b)
# [1, 2, 3, 4, 5, 7, 8, 9, 10]

Obs.:我没有收到你提到的错误。

于 2020-06-01T07:42:47.623 回答