对于一个int数组,请编写一个堆排序算法,对数组元素排序。
给定一个int数组A及数组的大小n,请返回排序后的数组。
测试样例:
[1,2,3,5,2,3],6
[1,2,2,3,3,5]
参考文档:堆排序
http://www.cnblogs.com/dolphin0520/archive/2011/10/06/2199741.html
我的提交
-- 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 A
def 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