# How Does Heap Data Structure Work?

//

Angela Bailey

How Does Heap Data Structure Work?

The heap data structure is a complete binary tree that satisfies the heap property. It is commonly used for efficient implementation of priority queues. In this article, we will explore how the heap data structure works and its key operations.

## Heap Property

A binary tree satisfies the heap property if it satisfies either the max-heap property or the min-heap property:

• Max-Heap Property: In a max-heap, for every node i, the value of i is greater than or equal to the values of its children.
• Min-Heap Property: In a min-heap, for every node i, the value of i is less than or equal to the values of its children.

The heap property ensures that the maximum (or minimum) element is always at the root of the heap.

## Complete Binary Tree

A complete binary tree is a binary tree in which all levels except possibly the last are completely filled, and all nodes are as far left as possible. This property allows us to represent a heap using an array.

## Array Representation

In an array representation of a binary tree, given an index i:

• The left child of i is located at index 2i + 1.
• The right child of i is located at index 2i + 2.
• The parent of i is located at index floor((i – 1) / 2).

This array representation allows us to access elements efficiently without using explicit pointers or references.

## Heapify

The process of creating a heap from an array is called heapify. Heapify can be performed in two ways:

• Bottom-up Approach: Starting from the last parent node, we compare the node with its children and swap if necessary to satisfy the heap property.
• Top-down Approach: Starting from the root, we compare the node with its children and swap if necessary. We repeat this process recursively for each subtree until the entire tree satisfies the heap property.

The time complexity of heapify is O(n), where n is the number of elements in the array.

## Key Operations

The key operations on a heap are:

• Insertion: To insert an element into a heap, we add it at the end of the array and then perform a “swim” operation to restore the heap property.
• Deletion: To delete an element from a heap, we replace it with the last element in the array and then perform a “sink” operation to restore the heap property.
• Peek: To retrieve the maximum (or minimum) element from a max-heap (or min-heap) without removing it, we simply return the root of the heap.

The time complexity of these operations depends on the height of the tree, which is O(log n), where n is the number of elements in the heap.

## Conclusion

The heap data structure provides efficient implementation of priority queues by maintaining elements in a complete binary tree satisfying either max-heap or min-heap property. Understanding how heaps work and their key operations is essential for efficient algorithm design and implementation.