1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
| ''' 堆排序算法 堆排序算法是在选择排序的基础上发展而来的。
'''
class HeapStruct_2(): def __init__(self,elements=[None],addre=0,capacity=0): self.elements = elements self.addre = addre self.capacity = capacity def MinHeapCreate(self,Capacity_Size): print(' 若插入数值,请确保插入数值在 0 以上 。结点容量为%d'%Capacity_Size) self.elements = [None] * (Capacity_Size+1) self.capacity = Capacity_Size self.elements[0] = self.MinData() print('self capacity = %s'%self.capacity) def MinData(self): return 0 def Insert(self,item): if self.IsFull(): print('最小堆已满') return i = self.addre + 1 if self.elements[0] >= item: print('插入数值大小小于下限') return while self.elements[i//2] > item: print(self.elements[i//2],item) self.elements[i] = self.elements[i//2] i //= 2 self.elements[i] = item self.addre += 1 def IsFull(self): if self.addre == self.capacity: print( self.addre,self.capacity) return 1 return 0 def IsEmpty(self): if self.addre == 0: return 1 return def DeleteMin(self): if self.IsEmpty(): print('最小堆已空。') return minitem = self.elements[1] temp = self.elements[self.addre] self.elements[self.addre] = None self.addre -= 1 parent = 1 while parent*2 <= self.addre: left_child = parent * 2 if self.addre != left_child and self.elements[left_child+1] < self.elements[left_child]: child = left_child + 1 else: child = left_child if self.elements[child] <= temp: self.elements[parent] = self.elements[child] parent = child elif self.elements[child] > temp: self.elements[parent] = temp return minitem self.elements[parent] = temp return minitem
''' 原始的堆排序算法。 '''
def Heap_Sort(A): N = len(A) h = HeapStruct_2() h.MinHeapCreate(12) BuildHeap(A,h) for i in range(N): A[i] = h.DeleteMin()
def BuildHeap(A,h): for a in A: h.Insert(a)
A_ = [1,5,6,2,4,3,8,9,7] Heap_Sort(A_) print('原始的堆排序 时间复杂度O(NlogN)、空间复杂度 2N,结构如下:\n',A_,'\n')
def Heap_Sort_new(A): N = len(A) for i in range(int(N/2),0,-1): PercDown(A,i,N-1) for i in range(N-1,0,-1): Swap(A,1,i) PercDown(A,1,i-1)
def PercDown(A,i,num): parent = i temp = A[i] while parent * 2 <= num: left_child = parent * 2 if num != left_child and A[left_child + 1] > A[left_child]: child = left_child + 1 else: child = left_child if A[child] >= temp: A[parent] = A[child] parent = child elif A[child] < temp: A[parent] = temp return A[parent] = temp
def Swap(A,a,b): temp = A[a] A[a] = A[b] A[b] = temp
A = [1,5,6,2,4,3,8,9,7] A.insert(0,-1) Heap_Sort_new(A) A.pop(0) print('用heapify堆化的堆排序 平均时间复杂度O( 2NlogN - O(NloglogN) )、空间复杂度 N,结构如下:\n',A,'\n')
|