快速排序未返回预期结果 - Python3

时间:2016-04-28 09:40:03

标签: python python-3.x

我一直致力于快速排序算法,该算法专门设置左侧的墙,当前元素位于墙的右侧,枢轴位于数据集的末尾。 排序将比较当前元素与pivot,并在每次大于pivot时递增当前元素。当它小于或等于枢轴时,它应该将当前元素与墙壁右侧的项目交换,并将墙壁向右移动一个位置。

这是我的代码:

def QuickSort(dataset, low, high):
    if (low >= high):
        return dataset
    else:
        #Set pivot to last element
        pivot = high
        #Set wall at first element
        wall = low
        #Loop through list - if current element is less or equal
        #to the pivot, swap current element with element right of wall
        #and move wall on.
        for i in range(high):
            if (dataset[i] <= pivot):
                temp = dataset[wall]
                dataset[wall] = dataset[i]
                dataset[i] = temp
                wall = wall + 1
                if wall >= high:
                    break

        #recursively call for subsequent part of list
        QuickSort(dataset, low, wall-1)
        QuickSort(dataset, wall, high)

dataset = [1,6,2,3,6,7,4,2,5]
dataset_length = len(dataset)
sorted_data = QuickSort(dataset, 0, dataset_length)
print(sorted_data)

input()

运行代码时,不会返回数据集,我无法确切地看到出错的地方。谢谢你的帮助。

1 个答案:

答案 0 :(得分:3)

pivot = high

这不会将数据透视设置为列表中的最后一个元素。相反,它将数据集的长度设置为9,因此将其更改为dataset[high - 1]

此外,您需要搜索大于pivot或小于pivot的元素的范围不是range(high),而是range(low, high),因为你会更深入地进行递归,列表的大小也会改变,也可以是它的起始和结束索引。

def QuickSort(dataset, low, high):
    if (low >= high):
        return
    #Set pivot to last element
    pivot = dataset[high - 1]
    #Set wall at first element
    wall = low
    #Loop through list - if current element is less or equal
    #to the pivot, swap current element with element right of wall
    #and move wall on.
    for i in range(low, high):
        if (dataset[i] <= pivot):
            temp = dataset[wall]
            dataset[wall] = dataset[i]
            dataset[i] = temp
            wall = wall + 1
            if wall >= high:
                break
         #recursively call for subsequent part of list
    QuickSort(dataset, low, wall - 1)
    QuickSort(dataset, wall, high)

dataset = [1,6,2,3,6,7,4,2,5]
dataset_length = len(dataset)
QuickSort(dataset, 0, dataset_length)
print(dataset)