python 堆排序算法
2023-02-18 16:44:50 时间
老高最近在准备面试,正好复习到堆排序,正好总结一下
堆排序的算法思路基本如下:
- 找到最后一个非叶子节点,进行第一次循环比较,找到第一个最值
- 将找到的最值移动到末尾,长度-1,root=0,继续排序n-1次
- 每次发生比较后需要在此循环比较,直到没有发生移动或者超过最大长度
- 比较的时间复杂度O(lgn),生成堆的时间复杂度为O(n),所以总的时间复杂度为O(nlgn)
- 堆排序是不稳定的排序
def build_heap(l):
l_len = len(l)
for i in range((l_len - 2) // 2, -1, -1):
re_heap(l, l_len, i)
def build_heap_min(l):
l_len = len(l)
for i in range((l_len - 2) // 2, -1, -1):
re_heap_min(l, l_len, i)
def re_heap(h, size, root):
larger = root
left = root * 2 + 1
right = left + 1
if left < size and h[left] > h[larger]:
larger = left
if right < size and h[right] > h[larger]:
larger = right
if larger != root:
# need change
h[larger], h[root] = h[root], h[larger]
# continue
re_heap(h, size, larger)
def re_heap_min(h, size, root):
min = root
left = root * 2 + 1
right = left + 1
if left < size and h[left] < h[min]:
min = left
if right < size and h[right] < h[min]:
min = right
if min != root:
# need change
h[min], h[root] = h[root], h[min]
# continue
re_heap_min(h, size, min)
def heap_sort(l):
build_heap(l)
l_len = len(l)
for i in range(l_len - 1, -1, -1):
l[0], l[i] = l[i], l[0]
re_heap(l, i, 0)
return l
def heap_sort_min(l):
build_heap_min(l)
l_len = len(l)
for i in range(l_len - 1, -1, -1):
l[0], l[i] = l[i], l[0]
re_heap_min(l, i, 0)
return l
if __name__ == '__main__':
l = [4, 5, 6, 34, 67, 475, 545, 567, 3454]
print heap_sort(l)
print '-' * 36
print heap_sort_min(l)
相关文章
- 实战案例丨分布式系统中如何用python实现Paxos
- 从零开始学习python | 实例讲解如何制作Python模式程序
- 如何正确使用Python临时文件
- Python中Round函数:怎么解释?怎么用?
- Docker DevOps实战:Docker+Jenkins+Python+Pytest+Allure(2)- Jenkins初始化、Jenkins插件、Jenkins配置、自动化测试
- Docker DevOps实战:Docker+Jenkins+Python+Pytest+Allure(1)- 创建Jenkins容器、安装Python环境、安装项目依赖类库、安装Allure报告插件
- Python - 生成requirement.text 文件
- Python 初学者必看:Python 异常处理集合
- 混合编程:如何用python11调用C++
- 知道Python中的字符串是什么吗?
- Python基础(十二):字典的详细讲解
- 搭建http文件服务器 - python3使用http.server搭建http文件服务器
- 25个关键技术点,带你熟悉Python
- 华为云“网红”语言Python课程来啦!
- 教你如何在Python中读,写和解析CSV文
- 热加载技术:修改Python代码并实时查看结果 ⛵
- 码神说Python安装及pycharm
- Python0基础(上)——期末不挂科
- Python0基础(中)——期末不挂科
- Python0基础(下)——期末不挂科