Algorithm Design Questions
The heap data structure is a complete binary tree that satisfies the heap property. The heap property states that for a max heap, the value of each node is greater than or equal to the values of its children, and for a min heap, the value of each node is less than or equal to the values of its children.
The operations performed on a heap include:
1. Insertion: To insert a new element into the heap, it is added as the last element in the tree and then "bubbled up" or "percolated up" to its correct position by comparing it with its parent and swapping if necessary. This operation has a time complexity of O(log n), where n is the number of elements in the heap.
2. Deletion: The root element, which is the maximum (in a max heap) or minimum (in a min heap), is removed from the heap. The last element in the tree is then moved to the root position and "bubbled down" or "percolated down" to its correct position by comparing it with its children and swapping if necessary. This operation also has a time complexity of O(log n).
3. Peek: This operation returns the value of the root element without removing it from the heap. It has a time complexity of O(1).
4. Heapify: This operation is used to convert an array into a heap. It starts from the last non-leaf node and performs the "bubbledown" operation on each node until the root is reached. This operation has a time complexity of O(n), where n is the number of elements in the array.
The heap data structure is commonly used in priority queues, sorting algorithms like heapsort, and graph algorithms like Dijkstra's algorithm.