簡體   English   中英

在 Python 中對陣列進行就地分區

[英]Partitioning an array in placein Python

我嘗試分區(就地)無序數組 a 和固定元素(樞軸)。

輸入:[1、3、6、1、5、4]

結果應如下所示: [1, 1, 3, 4, 5, 6 ]

相反,我得到了這個: [1, 6, 1, 3, 5, 4]

有沒有辦法遞歸地解決它?

這是我的代碼:

def swap(a, i, j):
    a[i], a[j] = a[j], a[i]

def Part(a, pivot):
    n = len(a)
    i = - 1
    j = 0
    for j in range(n):
        if a[j] <= a[pivot]: 
            swap(a, i + 1, j)
            i = i + 1
            j = j + 1
        else:
            j + 1
    swap(a, i+1, pivot)
    return i+1

此代碼完成您的工作。

def sort(testVariable, length):
    # Base case
    if length <= 1 :
        return
    
    # Recursive case
    # Sort first n-1 elements
    sort(testVariable, length - 1)

    # Insert last element at its correct position in sorted array
    lastElement = testVariable[length - 1] # fetch the last element
    temp = length - 2 # start finding its correct location from one element before it
    
    # Move elements of testVariable[0..i-1], that are greater than key, to one position ahead of their current position 
    while (temp >= 0 and testVariable[temp] > lastElement):
        testVariable[temp + 1] = testVariable[temp]
        temp = temp - 1

    testVariable[temp + 1] = lastElement # place the element in its correct position


# Driver Code
testVariable = [5, 4, 2, 3, 1, 1]
print("Original Array ---> " + str(testVariable))

sort(testVariable, len(testVariable))
print("Modified Array ---> " + str(testVariable))

暫無
暫無

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

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