Answered step by step
Verified Expert Solution
Question
1 Approved Answer
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!
Q Coding Question
We will be making an array based maxheap
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
A method to get a positions left childs index
A positions left child is in index pos
A method to get a positions right childs index
A positions right child is in index pos
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 to size
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
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started