首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >谁能说出我的快速排序代码中的错误是什么

谁能说出我的快速排序代码中的错误是什么
EN

Stack Overflow用户
提问于 2019-03-23 13:09:51
回答 2查看 84关注 0票数 1

谁能说出我的快速排序算法中的错误是什么?我使用两个点'left‘和'right’来与轴心进行比较,如果numsleft > numsright,则交换numsleft和numsright。当左索引大于右索引时,break和交换数字left和numspiovt,返回左索引。

代码语言:javascript
复制
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)

答案: 1,2,2,3,3,5,5,6,4

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-03-27 22:48:39

下面是代码中的几个bug,我已经为您重写了代码。你可以参考评论并运行一些测试来找出答案。

代码语言:javascript
复制
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')

我已经尽力帮助你了,希望你喜欢。

票数 0
EN

Stack Overflow用户

发布于 2019-03-23 13:15:47

要获得数组的中间索引,您应该将快速排序的枢轴设置为整数n/2。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55310815

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档