python - 合并排序,子列表保存在哪里?

标签 python algorithm sorting

我已经包含了我正在使用的代码。

我知道代码的开头会继续拆分子列表,直到您拥有单个值为止。单个值保存在变量 lefthalf 和 righthalf 中,然后按排序顺序合并。

代码如何合并两个包含两个元素的列表?正如我所见,这些子列表保存在称为 alist 的单独局部变量中,这些如何合并?

def mergeSort(alist):

    if len(alist)>1:
        mid = len(alist)//2
        lefthalf = alist[:mid]
        righthalf = alist[mid:]

        mergeSort(lefthalf)
        mergeSort(righthalf)

        i=0
        j=0
        k=0

        while i < len(lefthalf) and j < len(righthalf):
            if lefthalf[i] < righthalf[j]:
                alist[k]=lefthalf[i]
                i=i+1
            else:
                alist[k]=righthalf[j]
                j=j+1
            k=k+1


        while i < len(lefthalf): 
            alist[k]=lefthalf[i]
            i=i+1
            k=k+1


        while j < len(righthalf):
            alist[k]=righthalf[j]
            j=j+1
            k=k+1

最佳答案

第一个 while 循环从 lefthalfrighthalf 中选择一个较小的较小项目,直到两个列表中的一个用完。 (lefthalfrighthalf 每个都包含已排序的项目)

while i < len(lefthalf) and j < len(righthalf):
    if lefthalf[i] < righthalf[j]:
        # Pick the smallest item from `leftHalf` if has a smaller item
        alist[k]=lefthalf[i]
        i=i+1
    else:
        # Pick smallest item from `rightHalf`
        alist[k]=righthalf[j]
        j=j+1
    k = k + 1
    # `k` keeps track position of `alist`
    # (where to put the smallest item)
    # Need to increase the `k` for the next item

第二个、第三个while 循环将剩余的项目复制到alist。只会执行两个循环体中的一个;一个人在第一个 while 循环中筋疲力尽。


旁注:alist[k] = ... 更改 alist 的项目。

关于python - 合并排序,子列表保存在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38160564/

相关文章:

python - 在 cmd 模块 python 中调用菜单

python : Ramer-Douglas-Peucker (RDP) algorithm with number of points instead of epsilon

java - 如何在不使用 Collections.sort() 的情况下按值对 LinkedHashMap 进行排序?

python - 如何在Python中检查视频是否有声音?

python - 在 RTSP 设置后接收 RTP 数据包

algorithm - 给定长度的表达式数

algorithm - 递归算法的空间复杂度界限

r - 使用 dplyr 对随机交易列表进行排序

java - 按姓氏和顺序对行进行排序

python - 更改网格大小以匹配网格中框的大小