就地合并排序python

2j4z5cfb  于 2021-09-08  发布在  Java
关注(0)|答案(1)|浏览(473)

我正在尝试一种就地合并排序,它使用旋转对项目进行排序。问题在于,它适用于降序排列的两个项目数的幂,而不适用于其他排列或项目数:

def binary_search_middle(array, start, middle, end):
    a = 0
    b = min(middle - start, end - (middle + 1)) + 1
    M = (a + b) // 2

    while a < b:
        if array[middle - M] > array[(middle + 1) + M]:
            a = M + 1
        else:
            b = M
        M = (a + b) // 2

    return M

def rotate(array, start, end, size):
    for i in range(start, end + 1):
        array[i], array[i + size] = array[i + size], array[i]

def merge(array, start, middle, end):
    size  = binary_search_middle(array, start, middle, end) + 1
    left  = middle - (size - 1)
    right = (middle + 1) + (size - 1)

    while size > 0 and right <= end:
        rotate(array, left, middle, size)
        merge(array, middle + 1, right, end)
        end    = middle
        middle = left
        size   = binary_search_middle(array, start, middle, end)

def in_place_merge_sort(array):
    last = len(array) - 1
    size = 1

    while size <= last:
        for i in range(0, last + 1, 2 * size):
            middle = i + size - 1
            end    = min(middle + size, last)
            merge(array, i, middle, end)
        size = 2 * size

有什么问题吗?

cwtwac6a

cwtwac6a1#

在in_place_merge_sort中,我没有看到任何代码可以处理这样的情况:只剩下一次运行,在过程结束时没有任何东西要合并,即middle>=last。可能是这样的修复:

middle = i + size - 1          # in current code
        if(middle >= last):            # fix
            break                      # fix

相关问题