我对Quicksort稍加修改就陷入了经典的螺母和螺栓问题。我不知道为什么我的测试用例不匹配。
我正在使用Lomuto的分区函数,在螺母和螺栓的情况下应该基本相同,请期待我传入另一个数组的枢轴元素(分别为螺母或螺栓)的事实。
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))