#!/usr/bin/env python
# -*- coding: utf-8 -*-
import heapq
import copy
import datetime
import random
def get_max_heap(heap, size, root): # 在堆中做結構調整使得父節點的值大於子節點
left = 2 * root + 1
right = left + 1
larger = root
if left < size and heap[larger] < heap[left]: # 保證最大值不會被重新排序
larger = left
if right < size and heap[larger] < heap[right]: # 保證最大值不會被重新排序
larger = right
if larger != root: # 如果做了堆調整則larger的值等於左節點或者右節點的,這個時候做對調值操作
heap[larger], heap[root] = heap[root], heap[larger]
get_max_heap(heap, size, larger)
def build_heap(heap):
# 構造一個堆,將堆中所有數據重新排序
for index in xrange(len(heap) / 2 - 1, -1, -1): # 從第一個非葉子節點開始
get_max_heap(heap, len(heap), index)
def sort(heap):
build_heap(heap) # 獲得一個大頂堆
for index in xrange(len(heap) - 1, -1, -1):
heap[0], heap[index] = heap[index], heap[0] # 將最大值調到最后
get_max_heap(heap, index, 0) # size遞減,保證最大值不會被重新排序
return heap
if __name__ == '__main__':
# a = eval(raw_input('請輸入一個待排序列表\n'))
a = [random.randint(1, 2000) for i in range(1000)]
b = copy.deepcopy(a)
b_begin = datetime.datetime.now()
sort(b)
b_end = datetime.datetime.now()
print 'my method use %s' % (b_end - b_begin).total_seconds()
c = copy.deepcopy(a)
c_begin = datetime.datetime.now()
heapq.heapify(c)
c_end = datetime.datetime.now()
print 'inner method use %s' % (c_end - c_begin).total_seconds()
——————————————————————————————
my method use 0.011
inner method use 0.001
#可以看到,我們實現的排序算法在時間上不如內置的heapq.heapify()