Binary Heap & Heap Sort
Binary Heap & Heap Sort
Definition
• A Binary Heap is a complete Binary Tree which is
used to store data efficiently to get the max or min
element based on its structure.
• A Binary Heap is either Min Heap or Max Heap.
• Min Heap – Minimum root
• Max Heap – Maximum root
• The same property must be recursively true for all
nodes in Binary Tree.
Min Heap example
Min Heap Property: The value of each node is greater than or
equal to the value of its parent, with the minimum value at the root.
Max heap Example
Max Heap Property: The value of each node is less than or equal
to the value of its parent, with the maximum value at the root.
Binary Heap Array
Representation
• A Binary Heap is a Complete Binary Tree. A binary
heap is typically represented as an array.
• The root element will be at Arr[0].
• The below table shows indices of other nodes for the
ith node, i.e., Arr[i]:
• The traversal method use to achieve Array
representation is Level Order
Operations
• getMin(): It returns the root element of Min Heap. The
time Complexity of this operation is O(1). In case of a
maxheap it would be getMax().
• extractMin(): Removes the minimum element from
MinHeap. The time Complexity of this Operation
is O(log N) as this operation needs to maintain the
heap property (by calling heapify()) after removing the
root.
• decreaseKey(): Decreases the value of the key. The
time complexity of this operation is O(log N). If the
decreased key value of a node is greater than the
parent of the node, then we don’t need to do anything.
Otherwise, we need to traverse up to fix the violated
heap property.
Operations
• insert(): Inserting a new key takes O(log N) time. We
add a new key at the end of the tree. If the new key is
greater than its parent, then we don’t need to do
anything. Otherwise, we need to traverse up to fix the
violated heap property.
• delete(): Deleting a key also takes O(log N) time. We
replace the key to be deleted with the minimum infinite
by calling decreaseKey(). After decreaseKey(), the
minus infinite value must reach root, so we
call extractMin() to remove the key.
Heapify: