堆排序算法-python实现

1.定义

堆排序一开始需要将n个数据存进堆里,所需时间为O(nlogn)。排队过程中,堆从空堆的状态开始,逐渐被数据填满。由于堆的高度小于log2n ,所以插入一个数据需要的时间为O(logn)

2:时间复杂度:O(nlogn) 较快

3.空间复杂度:较复杂

4.Python 实现:

from collections import deque

def swap_param(L, i, j):
    L[i], L[j] = L[j], L[i]
    return L

def heap_adjust(L, start, end):
    temp = L[start]
    i = start
    j = 2 * i

    while j <= end:
        if (j < end) and (L[j] < L[j + 1]):
            j += 1
        if temp < L[j]:
            L[i] = L[j]
            i = j
            j = 2 * i
        else:
            break
    L[i] = temp

def heap_sort(L):
    L_length = len(L) - 1

    first_sort_count = L_length / 2
    for i in range(first_sort_count):
        heap_adjust(L, first_sort_count - i, L_length)

    for i in range(L_length - 1):
        L = swap_param(L, 1, L_length - i)
        heap_adjust(L, 1, L_length - i - 1)

    return [L[i] for i in range(1, len(L))]

def main():
    L = deque([50, 16, 30, 10, 60,  90,  2, 80, 70])
    L.appendleft(0)
    print heap_sort(L)

main()

猜你喜欢

转载自blog.csdn.net/qq_24403067/article/details/95230133