堆排序的思想在于,先根据数组建立一个大根堆或者小根堆,若为递增排序一般建立大根堆,之后每次将最后一个元素和堆顶元素调换,将剩下的元素调整为大根堆,依次调整到堆中只剩下一个节点,则数组中的元素为递增排序。
import random
class mySort(object):
def get_andomNumber(self,num):
lists = []
i = 0
while i < num:
lists.append(random.randint(0, 100))
i += 1
return lists
def adjust_heap(self,numbers,i,size):
lchild = 2*i+1
rchild = 2*i+2
max = i
if(i< int(size/2)):
if(lchild < size and numbers[lchild]>numbers[max]):
max = lchild
if(rchild < size and numbers[rchild]>numbers[max]):
max = rchild
if(max!=i):
numbers[max],numbers[i] = numbers[i],numbers[max]
self.adjust_heap(numbers,max,size)
def create_heap(self,numbers,size):
for i in range(int(size/2))[::-1]:
self.adjust_heap(numbers,i,size)
def heap_sort(self,numbers):
size = len(numbers)
self.create_heap(numbers,size)
for i in range(size)[::-1]:
numbers[i],numbers[0] = numbers[0],numbers[i]
self.adjust_heap(numbers,0,i)
return numbers
if __name__ == '__main__':
t = mySort()
num = t.get_andomNumber(10)
print(num)
print(t.heap_sort(num))