Question: Do in java please! Q 1 - Coding Question We will be making an array based max - heap The heap class will contain A

Do in java please!
Q1- Coding Question
We will be making an array based max-heap
The heap class will contain
A private int[] called Heap that will store the values
A private int for the heaps size
A private int for the max size of the heap
A constructor that takes the max size of the heap
A method to gets a nodes parents index
A positions parent is given by the index (pos -1)/2
A method to get a positions left childs index
A positions left child is in index (2* pos)+1
A method to get a positions right childs index
A positions right child is in index (2* pos)+2
A method to check is a position in the array is a leaf node
If the position is greater than half the size of the array and less than or equal to the total size of the array it will be a leaf node
A method to swap two nodes
It takes two position indexes and swaps them in the array
A void method called maxHeapify that recursively heapifies the given subtree
Takes the root node position as its parameter
Base case is that we reach a leaf node, return nothing
If our current positions value is less than its left child, or greater than its right child do the following:
If the left child is greater than the right child swap our current position
with the left child and maxHeapify the left child
Otherwise swap our current position with the right child and maxHeapify the right child
A method to insert into our heap
Add the new integer to the end of the array (use the size for the final index)
Make a temporary variable to represent which index we are on as we check all values in our heap
Using a while loop check if the the current node were on is greater than its parent
If it is then swap them and update the temp index to the index of itsparent
Increase the size variable
A method to print out the heap
For loop goes from i =0 to < size /2
Check if the left child of our heap at index i is not at an index greater than the size of the heap, and if it isnt then print it
Do the same for the right child
Discussion Question
What are some advantages and disadvantages of using heaps? How else can we implement heaps other than with arrays?

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!