Search operation on Min-Heap Data Structure

To search for an element in the min heap, a linear search can be performed over the array that represents the heap. However, the time complexity of a linear search is O(n), which is not efficient. Therefore, searching is not a commonly used operation in a min heap.

Here’s an example code that shows how to search for an element in a min heap using std::find():

C++
#include <bits/stdc++.h>
using namespace std;

int main()
{
    priority_queue<int, vector<int>, greater<int> >
        min_heap;
    // example max heap

    min_heap.push(10);
    min_heap.push(9);
    min_heap.push(8);
    min_heap.push(6);
    min_heap.push(4);

    int element = 6; // element to search for
    bool found = false;

    // Copy the min heap to a temporary queue and search for
    // the element
    std::priority_queue<int, vector<int>, greater<int> >
        temp = min_heap;
    while (!temp.empty()) {
        if (temp.top() == element) {
            found = true;
            break;
        }
        temp.pop();
    }

    if (found) {
        std::cout << "Element found in the min heap."
                  << std::endl;
    }
    else {
        std::cout << "Element not found in the min heap."
                  << std::endl;
    }

    return 0;
}
Java
import java.util.PriorityQueue;

public class GFG {
    public static void main(String[] args)
    {
        PriorityQueue<Integer> min_heap
            = new PriorityQueue<>();
        min_heap.add(
            3); // insert elements into the priority queue
        min_heap.offer(1);
        min_heap.offer(4);
        min_heap.offer(1);
        min_heap.offer(6);

        int element = 6; // element to search for
        boolean found = false;

        // Copy the min heap to a temporary queue and search
        // for the element
        PriorityQueue<Integer> temp
            = new PriorityQueue<>(min_heap);
        while (!temp.isEmpty()) {
            if (temp.poll() == element) {
                found = true;
                break;
            }
        }

        if (found) {
            System.out.println(
                "Element found in the min heap.");
        }
        else {
            System.out.println(
                "Element not found in the min heap.");
        }
    }
}
Python3
import heapq

min_heap = [1, 2, 3, 5, 6, 7, 8, 10]  # example min heap
heapq.heapify(min_heap)

element = 6  # element to search for
found = False

# Copy the min heap to a temporary list and search for the element
temp = list(min_heap)
while temp:
    if heapq.heappop(temp) == element:
        found = True
        break

if found:
    print("Element found in the min heap.")
else:
    print("Element not found in the min heap.")
C#
using System;
using System.Collections.Generic;

public class GFG {
    public static void Main()
    {
        var minHeap = new PriorityQueue<int>();
        // example min heap
        minHeap.Enqueue(4);
        minHeap.Enqueue(6);
        minHeap.Enqueue(8);
        minHeap.Enqueue(9);
        minHeap.Enqueue(10);

        int element = 6; // element to search for
        bool found = false;

        // Copy the min heap to a temporary queue and search
        // for the element
        var temp = new PriorityQueue<int>(minHeap);
        while (temp.Count > 0) {
            if (temp.Peek() == element) {
                found = true;
                break;
            }
            temp.Dequeue();
        }

        if (found) {
            Console.WriteLine(
                "Element found in the min heap.");
        }
        else {
            Console.WriteLine(
                "Element not found in the min heap.");
        }
    }
}
Javascript
// Example min heap
let minHeap = new PriorityQueue();
minHeap.enqueue(4);
minHeap.enqueue(6);
minHeap.enqueue(8);
minHeap.enqueue(9);
minHeap.enqueue(10);

let element = 6; // Element to search for
let found = false;

// Copy the min heap to a temporary queue and search for the element
let temp = new PriorityQueue(minHeap);
while (temp.size() > 0) {
    if (temp.peek() == element) {
        found = true;
        break;
    }
    temp.dequeue();
}

if (found) {
    console.log("Element found in the min heap.");
} else {
    console.log("Element not found in the min heap.");
}

Output
Element found in the min heap.

Complexity Analysis

The time complexity of this program is O(n log n), where n is the number of elements in the priority queue.

The insertion operation has a time complexity of O(log n) in the worst case because the heap property needs to be maintained. The search operation involves copying the priority queue to a temporary queue and then traversing the temporary queue, which takes O(n log n) time in the worst case because each element needs to be copied and popped from the queue, and the priority queue needs to be rebuilt for each operation.

The space complexity of the program is O(n) because it stores n elements in the priority queue and creates a temporary queue with n elements.

Introduction to Min-Heap – Data Structure and Algorithm Tutorials

A Min-Heap is defined as a type of Heap Data Structure in which each node is smaller than or equal to its children. 

The heap data structure is a type of binary tree that is commonly used in computer science for various purposes, including sorting, searching, and organizing data.

Introduction to Min-Heap – Data Structure and Algorithm Tutorials

Purpose and Use Cases of Min-Heap:

  • Implementing Priority Queue: One of the primary uses of the heap data structure is for implementing priority queues. 
  • Dijkstra’s Algorithm: Dijkstra’s algorithm is a shortest path algorithm that finds the shortest path between two nodes in a graph. A min heap can be used to keep track of the unvisited nodes with the smallest distance from the source node.
  • Sorting: A min heap can be used as a sorting algorithm to efficiently sort a collection of elements in ascending order.
  • Median finding: A min heap can be used to efficiently find the median of a stream of numbers. We can use one min heap to store the larger half of the numbers and one max heap to store the smaller half. The median will be the root of the min heap.

Similar Reads

Min-Heap Data structure in Different languages:

1. Min-Heap in C++...

Difference between Min Heap and Max Heap:

Min Heap Max Heap 1. In a Min-Heap the key present at the root node must be less than or equal to among the keys present at all of its children. In a Max-Heap the key present at the root node must be greater than or equal to among the keys present at all of its children. 2. In a Min-Heap the minimum key element is present at the root. In a Max-Heap the maximum key element is present at the root. 3. A Min-Heap uses the ascending priority. A Max-Heap uses the descending priority. 4. In the construction of a Min-Heap, the smallest element has priority. In the construction of a Max-Heap, the largest element has priority. 5. In a Min-Heap, the smallest element is the first to be popped from the heap. In a Max-Heap, the largest element is the first to be popped from the heap....

Internal Implementation of Min-Heap Data Structure:

A Min heap is typically represented as an array.  The root element will be at Arr[0]. For any ith node Arr[i]:Arr[(i -1) / 2] returns its parent node.Arr[(2 * i) + 1] returns its left child node.Arr[(2 * i) + 2] returns its right child node....

Operations on Min-heap Data Structure and their Implementation:

Here are some common operations that can be performed on a Heap Data Structure,...

1. Insertion in Min-Heap Data Structure:

Elements can be inserted into the heap following a similar approach as discussed above for deletion. The idea is to:...

2. Deletion in Min-Heap Data Structure:

Removing the smallest element (the root) from the min heap. The root is replaced by the last element in the heap, and then the heap property is restored by swapping the new root with its smallest child until the parent is smaller than both children or until the new root reaches a leaf node....

3. Peek operation on Min-Heap Data Structure:

To access the minimum element (i.e., the root of the heap), the value of the root node is returned. The time complexity of peek in a min-heap is O(1)....

4. Heapify operation on Min-Heap Data Structure:

A heapify operation can be used to create a min heap from an unsorted array. This is done by starting at the last non-leaf node and repeatedly performing the “bubble down” operation until all nodes satisfy the heap property....

5. Search operation on Min-Heap Data Structure:

To search for an element in the min heap, a linear search can be performed over the array that represents the heap. However, the time complexity of a linear search is O(n), which is not efficient. Therefore, searching is not a commonly used operation in a min heap....

Applications of Min-Heap Data Structure:

Heap sort: Min heap is used as a key component in heap sort algorithm which is an efficient sorting algorithm with a time complexity of O(nlogn).Priority Queue: A priority queue can be implemented using a min heap data structure where the element with the minimum value is always at the root.Dijkstra’s algorithm: In Dijkstra’s algorithm, a min heap is used to store the vertices of the graph with the minimum distance from the starting vertex. The vertex with the minimum distance is always at the root of the heap.Huffman coding: In Huffman coding, a min heap is used to implement a priority queue to build an optimal prefix code for a given set of characters.Merge K sorted arrays: Given K sorted arrays, we can merge them into a single sorted array efficiently using a min heap data structure....

Advantages of Min-heap Data Structure:

Efficient insertion and deletion: Min heap allows fast insertion and deletion of elements with a time complexity of O(log n), where n is the number of elements in the heap.Efficient retrieval of minimum element: The minimum element in a min heap is always at the root of the heap, which can be retrieved in O(1) time.Space efficient: Min heap is a compact data structure that can be implemented using an array or a binary tree, which makes it space efficient.Sorting: Min heap can be used to implement an efficient sorting algorithm such as heap sort with a time complexity of O(n log n).Priority Queue: Min heap can be used to implement a priority queue, where the element with the minimum priority can be retrieved efficiently in O(1) time.Versatility: Min heap has several applications in computer science, including graph algorithms, data compression, and database systems....

Contact Us