简体   繁体   English

Python中的Quicksort

[英]Quicksort in Python

L = [7, 12, 1, -2, 0, 15, 4, 11, 9]


def quicksort(L, low, high):
    if low < high:
        pivot_location = Partition(L, low, high)
        quicksort(L,low, pivot_location)
        quicksort(L,pivot_location + 1, high)
    return L

def Partition(L, low, high):
    pivot = L[low]
    leftwall = low
    for i in range(low + 1, high, 1):
        if L[i] < pivot:
            temp = L[i]
            L[i] = L[leftwall]
            L[leftwall] = temp
            leftwall += 1
    temp = pivot
    pivot = L[leftwall]
    L[leftwall] = temp
    return leftwall

print(quicksort(L, 0, len(L) - 1))

When I run the code it produces the following result: [-2, 0, 1, 4, 7, 11, 12, 15, 9]. 当我运行代码时,它将产生以下结果:[-2、0、1、4、7、11、12、15、9]。 One element is at the wrong position. 一个要素处于错误的位置。 If anyone could tell me where the problem is ? 如果有人能告诉我问题出在哪里?

I just changed this line of code and it worked fine: 我只是更改了这一行代码,它运行良好:

quicksort(L, 0, len(L))

instead of 代替

quicksort(L, 0, len(L) - 1)

Here I just show u another simple way to implement Q_Sort in Python: 在这里,我仅向您展示在Python中实现Q_Sort的另一种简单方法:

def q_sort(lst):
    return [] if not lst else q_sort([e for e in lst[1:] if e <= lst[0]]) + [lst[0]] + q_sort([e for e in lst[1:] if e > lst[0]])


L = [7, 12, 1, -2, 0, 15, 4, 11, 9]

print q_sort(L)

and we get: 我们得到:

[-2, 0, 1, 4, 7, 9, 11, 12, 15] [-2,0,1,4,4,7,9,11,12,15]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM