Python 对于螺母和螺栓问题,最好的分区实现是什么?

Python 对于螺母和螺栓问题,最好的分区实现是什么?,python,sorting,quicksort,Python,Sorting,Quicksort,我对Quicksort做了一点小小的修改,就被这个经典的螺母和螺栓问题难住了。我不明白为什么我的测试用例不匹配 我使用的是Lomuto的配分函数,在螺母和螺栓的情况下应该基本相同,除了我传入另一个数组的枢轴元素(分别是螺母或螺栓)之外 def分区(arr、开始、结束、螺母): ''返回基于数组的分区索引 在另一个数组的枢轴元素上。“” #要与轴值交换的轴位置;右边的第一个值 pi=开始 #从头到尾迭代 对于范围内的i(开始、结束): 如果arr[i] def partition(arr, sta

我对Quicksort做了一点小小的修改,就被这个经典的螺母和螺栓问题难住了。我不明白为什么我的测试用例不匹配

我使用的是Lomuto的配分函数,在螺母和螺栓的情况下应该基本相同,除了我传入另一个数组的枢轴元素(分别是螺母或螺栓)之外

def分区(arr、开始、结束、螺母): ''返回基于数组的分区索引 在另一个数组的枢轴元素上。“” #要与轴值交换的轴位置;右边的第一个值 pi=开始 #从头到尾迭代 对于范围内的i(开始、结束): 如果arr[i]
def partition(arr, start, end, nut):
    '''Return the partition index of an array based 
    on the pivot element of the other array.'''
    # pivot position to swap with pivot value; first value to the right
    pi = start
    # iterate from start to end
    for i in range(start, end):
        if arr[i] <= nut:  # current value <= pivot value
            # swap current and value at pivot position
            arr[i], arr[pi] = arr[pi], arr[i] 
            pi += 1  # update pivot position

    # Return the partition index of an array based on the pivot  
    # element of other array. 
    arr[end], arr[pi] = arr[pi], arr[end]
    final_pivot_index = pi
    return final_pivot_index

def qsortNutsandBolts(nuts, bolts, low, high):
    if high >= low:
        # choose a nut in [lo...hi] ideally, should be random or median
        choosen_nut = nuts[high] # or high for simplicity
        # partition bolts around the nuts's value as pivot position
        # return the *final position* of the matching bolt
        pi = partition(bolts, low, high, choosen_nut)
        # then, partition bolts around the chosen nut's final position
        # this results in the corresponding bolt also being in its final position
        _ = partition(nuts, low, high, bolts[pi])
        # nut and bolt at the pivot position match, solve the subproblem [lo...pivot-1] recursively
        qsortNutsandBolts(nuts, bolts, low, pi-1)
        # solve the subproblem [pivot+1...hi] recursively
        qsortNutsandBolts(nuts, bolts, pi+1, high)

def solve(nuts, bolts):
    start, end = 0, len(nuts)-1
    qsortNutsandBolts(nuts, bolts, start, end)
    return nuts, bolts 

nuts = [i for i in range(5)]
bolts = [i for i in range(5)]

random.shuffle(nuts)
random.shuffle(bolts)

print('Shuffled nuts: {0}'.format(nuts))
print('Shuffled Bolts: {0}'.format(bolts))
print('')

n, b = solve(nuts, bolts)

print('Sorted nuts: {0}'.format(n))
print('Sorted Bolts: {0}'.format(b))