博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
堆排序
阅读量:6974 次
发布时间:2019-06-27

本文共 1403 字,大约阅读时间需要 4 分钟。

对于一个int数组,请编写一个堆排序算法,对数组元素排序。

给定一个int数组A及数组的大小n,请返回排序后的数组。

测试样例:

[1,2,3,5,2,3],6

[1,2,2,3,3,5]

参考文档:堆排序

我的提交

-- coding:utf-8 --

class HeapSort:

def heapAdjust(self,A, i, n):
if i >= n // 2:
return
max = i
left = 2 * i
right = left + 1

if max <= n // 2:        if left < n and A[left] > A[max]:            max = left        if right < n and A[right] > A[max]:            max = right        if max != i:            A[max],A[i] = A[i],A[max]            self.heapAdjust(A, max, n)def heapBuild(self, A, n):    for i in range(int(n // 2))[::-1]:        self.heapAdjust(A, i, n)def heapSort(self, A, n):    # write code here    self.heapBuild(A, n)    for i in range(n)[::-1]:        A[0],A[i] = A[i],A[0]        self.heapAdjust(A, 0, i)    return A

if name == 'main':

hs = HeapSort()
print(hs.heapSort([32,103,24,88,95,70,97,15,102,6,79,46,51,37,93,108,9,58,53,58,79,36,58,91,78,58,61,81],28))
参考答案

-- coding:utf-8 --

class HeapSort:

def heapSort(self, A, n):

write code here

for i in range(n/2+1, -1, -1):        self.MaxHeapFixDown(A, i, n);    for i in range(n-1, -1, -1):        A[0], A[i] = A[i], A[0]        self.MaxHeapFixDown(A, 0, i)    return Adef MaxHeapFixDown(self, A, i, n):    tmp = A[i]    j = 2*i+1    while(j
A[j]: j+=1 if A[j] < tmp: break A[i] = A[j] i = j j = 2*i+1 A[i] = tmp

转载于:https://blog.51cto.com/13545923/2054467

你可能感兴趣的文章
Custome Message in MVC3.0
查看>>
Cisco 单臂路由配置
查看>>
数据库缓存管理器块替换
查看>>
dedecms个人中心调用数据库数据问题
查看>>
Confluence 6 Windows 中以服务方式自动重启修改运行服务的用户
查看>>
kettle使用笔记(ETL篇)
查看>>
What's new in Red Hat Enterprise Linux 6.2
查看>>
MDaemonV15 版本新特性介绍
查看>>
我的友情链接
查看>>
typescript中的泛型
查看>>
安装Jenkins
查看>>
tab键技巧小结
查看>>
我的友情链接
查看>>
数据库管理中文件的使用
查看>>
centos7下查找项目路径
查看>>
我的友情链接
查看>>
TurboMail邮件系统无缝集成OA办公系统
查看>>
菜刀Access数据库去除密码小工具
查看>>
关于mqtt学习
查看>>
[转]使用System Center 2012 Unified Installer安裝微軟私有雲管理套件(RC)
查看>>