MAX-HEAPIFY(A, i)
1 l ← LEFT(i)
2 r ← RIGHT(i)
3 if l ≤ heap-size[A] and A[l] > A[i]
4 then largest ← l
5 else largest ← i
6 if r ≤ heap-size[A] and A[r] > A[largest]
7 then largest ← r
8 if largest ≠ i
9 then exchange A[i] ↔ A[largest]
10 MAX-HEAPIFY(A, largest)
BUILD-MAX-HEAP(A)
1 heap-size[A] ← length[A]
2 for i ← ⌊length[A]/2⌋ downto 1
3 do MAX-HEAPIFY(A, i)
HEAPSORT(A)
1 BUILD-MAX-HEAP(A)
2 for i ← length[A] downto 2
3 do exchange A[1] ↔ A[i]
4 heap-size[A] ← heap-size[A] - 1
5 MAX-HEAPIFY(A, 1)
The HEAPSORT procedure takes time O(n lg n), since the call to BUILD-MAX-HEAP takes time O(n) and each of the n - 1 calls to MAX-HEAPIFY takes time O(lg n).
Heapsort is an excellent algorithm, but a good implementation of quicksort, usually beats it in practice.
Heapsort is an excellent algorithm, but a good implementation of quicksort, usually beats it in practice.
Heapsort is an excellent algorithm, but a good implementation of quicksort, usually beats it in practice.
priority-queue operation :
HEAP-MAXIMUM(A)
1 return A[1]
The procedure HEAP-MAXIMUM implements the MAXIMUM operation in Θ(1) time.
HEAP-EXTRACT-MAX(A)
1 if heap-size[A] < 1
2 then error "heap underflow"
3 max ← A[1]
4 A [1] ← A[heap-size[A]]
5 heap-size[A] ← heap-size[A] - 1
6 MAX-HEAPIFY(A, 1)
7 return max
The running time of HEAP-EXTRACT-MAX is O(lg n), since it performs only a constant amount of work on top of the O(lg n) time for MAX-HEAPIFY.
HEAP-INCREASE-KEY(A, i, key)
1 if key < A[i]
2 then error "new key is smaller than current key"
3 A [i] ← key
4 while i > 1 and A[PARENT(i)] < A[i]
5 do exchange A[i] ↔ A[PARENT(i)]
6 i ← PARENT(i)
The running time of HEAP-INCREASE-KEY on an n-element heap is O(lg n), since the path traced from the node updated in line 3 to the root has length O(lg n).
MAX-HEAP-INSERT(A, key)
1 heap-size[A] ← heap-size[A] + 1
2 A [heap-size[A]] ← -∞
3 HEAP-INCREASE-KEY(A, heap-size[A], key)
The running time of MAX-HEAP-INSERT on an n-element heap is O(lg n).
In summary, a heap can support any priority-queue operation on a set of size n in O(lg n)
time.