我对合并排序感兴趣。我编写了合并步骤以升序排序,并且可以正常工作(请参见下面的代码)。但是,当我尝试调整代码以使其以递减的方式排序时,我无法做到。我想反转i和j,但似乎不起作用。有人有什么想法吗?
def fusion(A,low,mid,high):
aux = [2,7,8,3,6,9]
i = low
j = mid+1
for k in range(low,high,1):
if i>mid:
A[k] = aux[j]
j = j+1
elif j > high:
A[k] = aux[i]
i = i+1
elif aux[i] <= aux[j]:
A[k] = aux[i]
i = i+1
else:
A[k] = aux[j]
j = j+1
return A
fusion([2,7,8,3,6,9],0,2,5)
输出为2,3,6,7,8,9,但我想要9,8,7,6,3,2
答案 0 :(得分:0)
这是“反向”变体:
def fusion(A, low, mid, high):
aux = A[::-1] # reverse A
i = low
j = mid + 1
for k in range(low, high, 1):
if i > mid:
aux[-k - 1] = A[j]
j += 1
elif j > high:
aux[-k - 1] = A[i]
i += 1
elif A[i] <= A[j]:
aux[-k - 1] = A[i]
i += 1
else:
aux[-k - 1] = A[j]
j += 1
return aux
print(fusion([2, 7, 8, 3, 6, 9], low=0, mid=2, high=5))
或者反转range()
:
def fusion(A, low, mid, high):
aux = A[::-1] # reverse A
i = low
j = mid + 1
for k in range(high, low, -1):
if i > mid:
aux[k] = A[j]
j += 1
elif j > high:
aux[k] = A[i]
i += 1
elif A[i] <= A[j]:
aux[k] = A[i]
i += 1
else:
aux[k] = A[j]
j += 1
return aux
或者只是...
list(reversed(fusion([2, 7, 8, 3, 6, 9], 0, 2, 5)))