本文共 1403 字,大约阅读时间需要 4 分钟。
对于一个int数组,请编写一个堆排序算法,对数组元素排序。
给定一个int数组A及数组的大小n,请返回排序后的数组。[1,2,3,5,2,3],6
[1,2,2,3,3,5]参考文档:堆排序
我的提交
class HeapSort:
def heapAdjust(self,A, i, n):if i >= n // 2:returnmax = ileft = 2 * iright = left + 1if 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))参考答案class HeapSort:
def heapSort(self, A, n):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(jA[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