Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Lesson 5: Minimum Heap Implementation Min Heap in Java A Min-Heap is a complete binary tree in which the value in each internal node is

Lesson 5: Minimum Heap Implementation

Min Heap in Java

A Min-Heap is a complete binary tree in which the value in each internal node is smaller than or equal to the values in the children of that node. Mapping the elements of a heap into an array is trivial: if a node is stored a index k, then its left child is stored at index 2k + 1 and its right child at index 2k + 2.

Example of Min Heap:

 5 13
 / \ / \ 
 10 15 16 31 
 / / \ / \
 30 41 51 100 41

How is Min Heap represented? A Min Heap is a Complete Binary Tree. A Min heap is typically represented as an array. The root element will be at Arr[0]. For any ith node, i.e., 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:

  1. getMin(): It returns the root element of Min Heap. Time Complexity of this operation is O(1).
  2. extractMin(): Removes the minimum element from MinHeap. Time Complexity of this Operation is O(Log n) as this operation needs to maintain the heap property (by calling heapify()) after removing root.
  3. insert(): Inserting a new key takes O(Log n) time. We add a new key at the end of the tree. If new key is larger than its parent, then we dont need to do anything. Otherwise, we need to traverse up to fix the violated heap property.

Below is the implementation of Min Heap in Java

Source Code

Output

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Sams Teach Yourself Beginning Databases In 24 Hours

Authors: Ryan Stephens, Ron Plew

1st Edition

067232492X, 978-0672324925

Students also viewed these Databases questions

Question

What does Processing of an OLAP Cube accomplish?

Answered: 1 week ago