Python quicksort TypeError

时间:2018-09-03 11:06:27

标签: python sorting typeerror quicksort

以下是我的代码引发的错误:

 File "python", line 39, in <module>
  File "python", line 8, in quicksort
  File "python", line 8, in quicksort
TypeError: unsupported operand type(s) for -: 'NoneType' and 'int'

以下是我的快速排序代码:

#!/usr/bin/python
# -*- coding: utf-8 -*-

def quicksort(arr, beg, end):
    if beg < end:
        pivot = partition(arr, beg, end)
        quicksort(arr, beg, pivot - 1)
        quicksort(arr, pivot + 1, end)

def partition(arr, beg, end):
    left = beg
    right = end
    loc = beg
    while arr[loc] <= arr[right] and loc != right:
        right = right - 1
    if loc == right:
        return loc
    elif arr[loc] > arr[right]:
        (arr[loc], arr[right]) = (arr[right], arr[loc])
        loc = right

    while arr[loc] >= arr[left] and loc != left:
        left = left + 1
    if loc == left:
        return loc
    elif arr[loc] < arr[left]:
        (arr[loc], arr[left]) = (arr[left], arr[loc])
        loc = left

y = [9,7,5,1,5]
quicksort(y, 0, 4)
print(y)

2 个答案:

答案 0 :(得分:2)

您不能从 different types Noneint)中减去2个变量。
之所以得到None,是因为并非partition函数的所有路径都返回值。
我在其末尾添加了一个return语句,这对我来说最有意义:

#!/usr/bin/python
# -*- coding: utf-8 -*-

def quicksort(arr, beg, end):
    if beg < end:
        pivot = partition(arr, beg, end)
        quicksort(arr, beg, pivot - 1)
        quicksort(arr, pivot + 1, end)

def partition(arr, beg, end):
    left = beg
    right = end
    loc = beg
    while arr[loc] <= arr[right] and loc != right:
        right = right - 1
    if loc == right:
        return loc
    elif arr[loc] > arr[right]:
        (arr[loc], arr[right]) = (arr[right], arr[loc])
        loc = right

    while arr[loc] >= arr[left] and loc != left:
        left = left + 1
    if loc == left:
        return loc
    elif arr[loc] < arr[left]:
        (arr[loc], arr[left]) = (arr[left], arr[loc])
        loc = left

    return loc


y = [9,7,5,1,5]
quicksort(y, 0, 4)
print(y)  # >>> [1, 5, 5, 7, 9]

但是,我没有检查每种情况下代码逻辑的正确性。
您可以检查this thread来查看快速排序在python中的实现。

答案 1 :(得分:1)

您不会从函数partition返回任何内容。并且已将其分配给pivot变量。这就是问题所在。照看您应该返回的值。