堆排序的python实现

#!/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()

 

posted @ 2018-07-28 16:10  Small_office  阅读(1421)  评论(0编辑  收藏  举报