算法原理 第六章 堆排序

来源:互联网 发布:51自学网单片机 编辑:程序博客网 时间:2024/06/03 14:24

Heap

Definition of Heap:

Array A[]
NODE(i): i
PARENT(i): lower(i / 2)
LEFT(i): 2i
RIGHT(i): 2i + 1
MaxHeap:
A[PARENT(i)] >= A[i]
MinHeap:
A[PARENT(i)] <= A[i]


Max-Heapify

Find out the largest number from pos i and its two children, set that to pos i, iterative the process till no need to exchange.
Time Complexity O(lg(N))

MAX-HEAPIFY(A, i)    l = LEFT(i)    r=RIGHT(i)if l <= A.heap-size and A[l] > A[i]    largest = lif l <= A.heap-size and A[r] > A[largest]    largest = rif largest != i    exchange A[i] with A[largest]    MAX-HEAPIFY(A, largest)

Build Max-Heap

Time Complexity O(N)

BUILD-MAX-HEAP(A)A.heap-size = A.lengthfor i = lower(A.length / 2) downto 1    MAX-HEAPIFY(A, i)

Heap Sort

Time Complexity O(Nlg(N))

HEAP-SORT(A)    BUILD-MAX-HEAP(A)    for i = A.length downto 2        exchange A[1] with A[i]        A.heap-size = A.heap-size - 1        MAX-HEAPIFY(A, 1)
0 0