Python 如何修改合并排序代码以从最大到最小排序
我知道这很琐碎,但我找不到解决方法。我有一个从最小到最大排序的合并排序代码,现在我被要求修改代码,从最大到最小排序,但似乎找不到我的方法。请帮忙,谢谢 以下是注释代码:Python 如何修改合并排序代码以从最大到最小排序,python,sorting,merge,Python,Sorting,Merge,我知道这很琐碎,但我找不到解决方法。我有一个从最小到最大排序的合并排序代码,现在我被要求修改代码,从最大到最小排序,但似乎找不到我的方法。请帮忙,谢谢 以下是注释代码: 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
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]))
但我预计会出版:
[9, 8, 7, 6, 5, 4, 3, 2, 1]
提前感谢您只在代码中的一个位置进行比较:在合并期间,当您比较
左[0]
和右[0]
时。颠倒比较的意义将颠倒整体排序。因此,为了按降序排序,将left[0]
和right[0]
中的较大者添加到输出中,即如果left[0]>right[0]:最新的.append(left[0])
只需在left[0]
和right[0]之间交换
如果这不明显,我应该这么做……我是否应该相信你编写了代码和解释,但却无法将代码更改为代码?@StefanPochmann他们没有声称自己编写了代码。这显然是个家庭作业。@user8964866-为了保持稳定性,比较应该是left[0]>=right[0]
。如果元素相等,则要移动左侧元素以保持相等元素的原始顺序。
[9, 8, 7, 6, 5, 4, 3, 2, 1]