美文网首页
Python堆排序

Python堆排序

作者: Timeless_ | 来源:发表于2021-05-12 01:03 被阅读0次
def sift(nums, low, high):
    # 构造大根堆(假设左右子树已是大根堆)。
    # 索引由0开始。

    # 递归版本,空间复杂度不为O(1)
    # left, right = 2*low+1, 2*low+2
    # large_index = low
    # if left<=high and nums[low]<nums[left]:
    #     large_index = left
    # if right<=high and nums[left]<nums[right]:
    #     large_index = right
    # if large_index != low:
    #     nums[low], nums[large_index] = nums[large_index], nums[low]
    #     sift(nums, large_index, high)

    # 非递归版本,空间复杂度O(1)
    i, j = low, low*2+1     # R[j]是R[i]的左孩子
    tmp = nums[i]   # tmp保存根节点的值
    while j <= high:
        if j < high and nums[j] < nums[j+1]:
            j += 1
        if tmp < nums[j]:
            nums[i] = nums[j]
            i = j
            j = 2*i+1
        else:
            break
    nums[i] = tmp


def HeapSort(nums):
    low, high = 0, len(nums)-1
    i = len(nums)//2-1  # 最大非叶节点索引(索引由0开始)
    while i >= 0:
        sift(nums, i, high)
        i -= 1
    for i in range(high, 0, -1):
        nums[0], nums[i] = nums[i], nums[0]
        sift(nums, 0, i-1)
    return nums


inputs = [1, 2, 34, 35, 23, 56, 2, 13]
print(HeapSort(inputs))    # [1, 2, 2, 13, 23, 34, 35, 56]

相关文章

  • python实现堆排序(HeapSort)

    python实现【堆排序】(HeapSort) 算法原理及介绍 堆排序(Heapsort)是指利用堆这种数据结构所...

  • 堆排序python

  • Python 堆排序

  • Python 堆排序

  • Python堆排序

  • 堆排序-python

    复习之前学过的堆排序,发现掌握的不是特别牢固,又仔细阅读了几篇博文,整理出来这篇记录。 1 堆排序介绍 1.1 与...

  • python堆排序

    实现了python的堆排序利用堆的特性,实现了在10000个数的列表中,找出最小的10个数,并和传统的冒泡排序进行...

  • 每周一个 Python 模块 | heapq

    专栏地址:每周一个 Python 模块 heapq 实现了适用于 Python 列表的最小堆排序算法。 堆是一个树...

  • 堆排序Python实现

    堆排序作是基本排序方法的一种,类似于合并排序而不像插入排序,它的运行时间为O(nlogn),像插入排序而不像合并排...

  • python堆排序heapq

    heapq模块实现了一个适用于Python列表的最小堆排序算法。 堆是一种树形数据结构,其中子节点与父节点之间是一...

网友评论

      本文标题:Python堆排序

      本文链接:https://www.haomeiwen.com/subject/mdcbtctx.html