大顶堆进行升序排序的python实现
2016-04-07 16:41
633 查看
#!/usr/bin/env python # -*- coding: utf-8 -*- # 将前l个节点构成的树的第i个节点调整为大顶堆 # base 1 def heap_adjust(lists,i,l): left,right=2*i-1,2*i max=i-1 if left<l and lists[max]<lists[left]: max=left if right<l and lists[max]<lists[right]: max=right if max!=i-1: lists[max],lists[i-1]=lists[i-1],lists[max] heap_adjust(lists,max+1,l) #子树有可能变成非大顶堆了,继续调整 def heap_sort(lists): # 将lists调整成一个大顶堆 for i in range(len(lists)/2,0,-1): heap_adjust(lists,i,len(lists)) for i in range(len(lists),0,-1): lists[0], lists[i - 1] = lists[i - 1], lists[0] #将堆顶记录和当前未经排序子序列的最后一个记录交换 heap_adjust(lists,1,i-1); #将lists[1...i-1]重新调整为大顶堆 lists=[int(x) for x in raw_input().split()] heap_sort(lists) print lists
相关文章推荐
- 初学python(对比java语言不同) 第四篇
- leetcode [python] 【338】Counting Bits
- [LeetCode]题解(python):139-Word Break
- python爬虫系列文章
- A Byte of Python 笔记(11)异常:try..except、try..finally
- python 学习笔记1(序列;if/for/while;函数;类)
- [LeetCode]题解(python):138-Copy List with Random Pointer
- [LeetCode]题解(python):137-Single Number II
- Sublime Text 3 配置python开发环境遇见的问题
- Win7下Python2.7环境安装paramiko模块
- python 列表、元组、字典
- 初学python(对比java语言不同) 第三篇
- Python SMTP发送邮件 - 带附件
- 在ipython notebook 上测试 ImportError: No module named _caffe
- Python3.4 用 BeautifulSoup 爬虫 Navigable String类型转换
- python学习笔记(xlwt/xlrd下载安装)
- Python列表
- Python通用序列操作
- LeetCode Best Time to Buy and Sell Stock
- Python Paramiko模块安装和使用