📜  门| GATE CS 2018 |问题 29(1)

📅  最后修改于: 2023-12-03 14:58:20.258000             🧑  作者: Mango

Gate CS 2018 | Question 29

Introduction

The question is related to the implementation of Heap data structure. You are given a heap with n elements, and you need to perform insert and delete operations on it.

Problem statement

You are given an array of n elements, and a heap. You need to implement the following operations on it:

  1. insert(x): insert an element in the heap
  2. delete(x): delete an element from the heap

The heap starts with n elements, and the value of n is not given to you.

Approach

The given problem can be solved using a Max Heap data structure. Max Heap data structure is a complete binary tree in which the value of each parent node is larger than its children.

Insert Operation

To perform insert operation, we add the new element to the end of the heap, and then we compare the value of the newly added element with its parent. If the value of the newly added element is greater than its parent, we swap them until the Max Heap property is satisfied.

insert(x):
    heap.append(x)
    currentIndex = n
    while(currentIndex > 0 and heap[(currentIndex-1)/2] < heap[currentIndex]):
        swap(heap[(currentIndex-1)/2], heap[currentIndex])
        currentIndex = (currentIndex-1)/2
Delete Operation

To perform delete operation, we first search for the element we want to delete. Once we find the element, we replace it with the last element of the heap, and then we remove the last element. Next, we compare the value of the new element with its children, and if we find any child that has a greater value than it, we swap them until the Max Heap property is satisfied.

delete(x):
    currentIndex = heap.indexOf(x)
    if(currentIndex == -1):
        return
    heap[currentIndex] = heap[n-1]
    heap.pop_back()
    n -= 1
    while((2*currentIndex+2)<n and (heap[currentIndex] < heap[2*currentIndex+1] or heap[currentIndex] < heap[2*currentIndex+2])):
        if(heap[2*currentIndex+1] > heap[2*currentIndex+2]):
            swap(heap[currentIndex], heap[2*currentIndex+1])
            currentIndex = 2*currentIndex+1
        else:
            swap(heap[currentIndex], heap[2*currentIndex+2])
            currentIndex = 2*currentIndex+2
Conclusion

In the above approach, we have implemented insert and delete operations on a Max Heap data structure in C++. The time complexity of both operations is O(log n).