快速排序递归错误

时间:2016-08-10 03:37:08

标签: python recursion

我的想法: 我正在尝试使用python实现快速排序。 我将第一个元素设置为pivot。 如果左标记的元素大于枢轴,那么我开始移动右标记以找到小于枢轴的元素,然后交换。 如果右标记小于左标记,则用右标记元素交换枢轴。 然后用pivot分隔列表。并重复这一步

问题: 我的代码可以像我想象的那样将列表分成两个列表。但当它返回时,它会以某种方式复制元素几次并使其错误。我不熟悉递归,也找不到问题。

def quick_sort(lst):
    front = []
    rear = []
    temp = 0
    pivot = lst[0]
    i = 1                 #leftmark
    j = len(lst)-1        #rightmark
    if len(lst) == 1:
        return lst
    while i<=j:
        if lst[i]<pivot:
            i+=1
        else:
            if lst[j]>pivot:
                j-=1
            elif lst[j] == pivot:
                break
            else:
                temp = lst[i]
                lst[i] = lst[j]
                lst[j] = temp

    '''if j<i  (rightmark < leftmark) swap pivot with position j'''
    temp = pivot
    pivot = lst[j]
    lst[j] = temp
    lst[0] = pivot
    front = lst[0:j+1]
    rear = lst[i:len(lst)+1]
    return quick_sort(front) + [pivot] + quick_sort(rear)

1 个答案:

答案 0 :(得分:0)

您正在将列表切成错误。您应该将lst[i:len(lst)+1]替换为lst[ j + 1 : ],将j替换为:,因为数据透视位于from the start位置,您应该忽略它(此处为{{}}之前的空虚{1}}代表:till the end代表temp后)。 最后但同样重要的是,考虑使用元组交换而不是temp = a a = b b = temp var,例如:

a, b = b, a

可以用一个衬垫替换

def quick_sort(lst):
    if lst:
        pivot = lst[0]
        i = 1                 #leftmark
        j = len(lst)-1        #rightmark
        if len(lst) == 1:
            return lst
        while i <= j:
            if lst[i] < pivot:
                i += 1
            elif lst[j]>pivot:
                    j-=1
            elif lst[j] == pivot:
                break
            else:
                lst[i], lst[j] = lst[j], lst[i]
        '''if j<i  (rightmark < leftmark) swap pivot with position j'''
        lst[0], lst[j] = lst[j], lst[0]
        front = lst[ : j ]
        rear = lst[ j+1 : ]
        return quick_sort(front) + [ pivot ] + quick_sort(rear)
    return []

这是我的最终工作代码:

>>> quick_sort([1,3,4,2,6,9,0])
[0, 1, 2, 3, 4, 6, 9]
@echo off
Title Multi Ping Tester
set URLS=www.twitter.com www.google.com www.facebook.com
For %%a in (%URLS%) do call :test_ping %%a
Exit /b
::**********************************************************
:test_ping
cls
If Exist %1.txt Del %1.txt
start cmd.exe "/c ping -4 -a %1 >> %1.txt"                 
Exit /b
::**********************************************************
相关问题