1. Heaps: Introduction and Properties
A heap is a specialized binary tree-based data structure that satisfies the heap property. There are two types of heaps:
- Max-Heap: The key at a parent node is always greater than or equal to the keys of its children. In a max-heap, the maximum element is always at the root.
- Min-Heap: The key at a parent node is always smaller than or equal to the keys of its children. In a min-heap, the minimum element is always at the root.
Heap Properties:
- Binary Tree Structure: A heap is a complete binary tree, meaning all levels are fully filled except possibly the last, which is filled from left to right.
- Heap Property: For a max-heap, the parent node must always be larger than its children. For a min-heap, the parent node must always be smaller than its children.
- Efficient Operations: Operations like insertion, deletion, and access to the largest (or smallest) element are efficient with time complexity of O(log n).
2. Priority Queues: Definition and Usage
A priority queue is an abstract data type that operates similarly to a regular queue but with an additional feature: each element has a priority. Elements are dequeued based on their priority rather than their insertion order.
Types of Priority Queues:
- Max-Priority Queue: Elements are dequeued based on the highest priority (larger numbers or values).
- Min-Priority Queue: Elements are dequeued based on the lowest priority (smaller numbers or values).
Example Use Cases:
- Task Scheduling: In an operating system, processes with higher priorities are executed first.
- Graph Algorithms: Used in algorithms like Dijkstra’s shortest path or Prim’s minimum spanning tree.
3. Heap Sort
Heap Sort is a comparison-based sorting algorithm that uses a heap to sort an array.