如何修改我的合并排序代码以从最大到最小排序
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何修改我的合并排序代码以从最大到最小排序相关的知识,希望对你有一定的参考价值。
我知道这是微不足道的,但无法找到我的方法。我有这个合并排序代码,从最小到最大排序,现在我被要求修改代码从最大到最小排序,但似乎无法找到我的路。请任何帮助将不胜感激。
这是评论的代码:
def mergesort(lst):
#Then, what does it do? mergesort should recursively
#run mergesort on the left and right sides of lst until
#it's given a list only one item. So, if lst has only
#one item, we should just return that one-item list.
if len(lst) <= 1:
return lst
#Otherwise, we should call mergesort separately on the
#left and right sides. Since each successive call to
#mergesort sends half as many items, we're guaranteed
#to eventually send it a list with only one item, at
#which point we'll stop calling mergesort again.
else:
#Floor division on the length of the list will
#find us the index of the middle value.
midpoint = len(lst) // 2
#lst[:midpoint] will get the left side of the
#list based on list slicing syntax. So, we want
#to sort the left side of the list alone and
#assign the result to the new smaller list left.
left = mergesort(lst[:midpoint])
#And same for the right side.
right = mergesort(lst[midpoint:])
#So, left and right now hold sorted lists of
#each half of the original list. They might
#each have only one item, or they could each
#have several items.
#Now we want to compare the first items in each
#list one-by-one, adding the smaller to our new
#result list until one list is completely empty.
newlist = []
while len(left) and len(right) > 0:
#If the first number in left is lower, add
#it to the new list and remove it from left
if left[0] < right[0]:
newlist.append(left[0])
del left[0]
#Otherwise, add the first number from right
#to the new list and remove it from right
else:
newlist.append(right[0])
del right[0]
#When the while loop above is done, it means
#one of the two lists is empty. Because both
#lists were sorted, we can now add the remainder
#of each list to the new list. The empty list
#will have no items to add, and the non-empty
#list will add its items in order.
newlist.extend(left)
newlist.extend(right)
#newlist is now the sorted version of lst! So,
#we can return it. If this was a recursive call
#to mergesort, then this sends a sorted half-
#list up the ladder. If this was the original
#call, then this is the final sorted list.
return newlist
#Let's try it out!
print(mergesort([2, 5, 3, 8, 6, 9, 1, 4, 7]))
这打印
[1, 2, 3, 4, 5, 6, 7, 8, 9]
但我预计会打印:
[9, 8, 7, 6, 5, 4, 3, 2, 1]
提前致谢
答案
您只在代码中的一个位置进行比较:在合并期间,当您比较left[0]
和right[0]
时。扭转比较意识将扭转整体排序。因此,为了按递减顺序排序,将较大的left[0]
和right[0]
添加到输出中,即,如果left[0] > right[0]: newest.append(left[0])
。
以上是关于如何修改我的合并排序代码以从最大到最小排序的主要内容,如果未能解决你的问题,请参考以下文章
codeforces733D. Kostya the Sculptor 偏序cmp排序,数据结构hash,代码简化