谁能告诉我快速排序代码中的错误是什么

时间:2019-03-23 05:09:51

标签: python algorithm sorting quicksort

谁能告诉我快速排序算法中的错误? 我使用两点“左”和“右”与数据透视表进行比较,并且当nums [left]> nums [right]时交换nums [left]和nums [right]。当左索引大于右索引时,中断并交换nums [left]和nums [piovt],返回左索引。

nums = [3,2,3,1,2,4,5,5,6]
n = len(nums)

def partition(nums,left,right,pivot):
    while left<right:
        if left<right and nums[left]<=nums[pivot]:
            left += 1
        if left<right and nums[right]>=nums[pivot]:
            right -= 1
        elif nums[left]>nums[right]:
            nums[left],nums[right] = nums[right],nums[left]
            left += 1
            right -= 1
    nums[left],nums[pivot] = nums[pivot],nums[left]
    return left

def quicksort(nums,low,high,pivot):
    if low<high:
        pos = partition(nums,low,high,pivot)
        quicksort(nums,low,pos-2,pos-1)
        quicksort(nums,pos+1,high-1,high)
    return nums

quicksort(nums,0,n-2,n-1)

print(nums)

ans:[1、2、2、3、3、5、5、6、4]

2 个答案:

答案 0 :(得分:0)

要获取数组的中间索引,应将quicksort的枢轴设置为整数n / 2。

答案 1 :(得分:0)

这是您代码中的几个错误,我已为您重写了代码。您可以参考评论并进行一些测试以找出答案。

import random

# two pointers solution, choose the last one as pivot
def partition(nums, left, right, pivot):
    while left < right:
        # here should change < to <=, because if pivot is larger than all in nums[left:right+1], should swap nums[left] with nums[pivot]
        # here I change if to while, because you should traverse the pointer to find the place which is invalid in partition
        while left <= right and nums[left] <= nums[pivot]:
            left += 1
        # here I change if to while, same reason above
        while left < right and nums[right] > nums[pivot]:
            right -= 1
        # you should not use elif here, because you have two ifs, the first if does not work here
        if left < right:
            nums[left], nums[right] = nums[right], nums[left]
    nums[left], nums[pivot] = nums[pivot], nums[left]
    return left


def quicksort(nums, low, high, pivot):
    if low < high:
        pos = partition(nums, low, high, pivot)
        quicksort(nums, low, pos - 2, pos - 1)
        # here is another problem: notice that nums[pivot] is the last element, not the nums[high]
        quicksort(nums, pos + 1, high, high + 1)
    return nums


if __name__ == '__main__':
    for _ in range(100):
        nums = [random.randrange(1, 100) for _ in range(10000)]
        n = len(nums)
        if sorted(nums) != quicksort(nums, 0, n - 2, n - 1):
            print('incorrect')
    print('success')

我已尽力帮助您,希望您喜欢它。