簡體   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))

當我運行代碼時,它將產生以下結果:[-2、0、1、4、7、11、12、15、9]。 一個要素處於錯誤的位置。 如果有人能告訴我問題出在哪里?

我只是更改了這一行代碼,它運行良好:

quicksort(L, 0, len(L))

代替

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

在這里,我僅向您展示在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)

我們得到:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM