Question

// CMPS 390 // MinHeap.java // Complete 4 methods: getMin, add, removeMin, reheap public class MinHeap { private Comparable aCMPS 390 // MinHeapDriver.java // Kuo-pao Yang /* s = {D, E, I, C, H, A, E, J, B, G}; DGI E The Min Heap

0 0
Add a comment Improve this question Transcribed image text
Answer #1

You are using comparable class which is not declared and adding String values into heap. So, for better understanding I am using String array instead of comparable array, if you have comparable class then change the declarations from String to comparable. Since we are using String at the place of null I am returning empty string("")

public void add(String newEntry){

if(lastIndex==heap.length-1){

System.out.println("Heap is already full");

return;

}

//Add the element at the end of the heap

heap[++lastIndex]=newEntry;
int current=lastIndex;

//Check whether it's parent element is greater or not If yes then run the loop until the condition is false.
while(current>1 && heap[current].compareTo(heap[current/2])<0){

String temp=heap[current];
heap[current]=heap[current/2];
heap[current/2]=temp;
current=current/2;

}

}

public String getMin(){

//Min element will be the starting element of the heap

String root="";
if(isEmpty()) return root;
root=heap[1];
return root;

}

public String removeMin(){

String root="";
if(isEmpty()) return root;
root=heap[1];

//replace the 1st element with the last element and use reheap(1) as we changed 1st element
heap[1]=heap[lastIndex];
heap[lastIndex]="";
--lastIndex;
reheap(1);
return root;

}

public void reheap(int index){

//check whether the index is the leaf element or not

if(!(index >= (lastIndex / 2) && index <= lastIndex)){

int left=2*index;
int right=2*index+1;

//Compare the parent element with leftchild and right child
if(heap[index].compareTo(heap[left])>0 || heap[index].compareTo(heap[right])>0){

//If left child is the smallest among 3 then swap(left child, parent elements) and recursively call for the left child element

if(heap[left].compareTo(heap[right])<0){

String temp=heap[index];
heap[index]=heap[left];
heap[left]=temp;
reheap(2*index);

}

//Similarly to the right child element

else{

String temp=heap[index];
heap[index]=heap[right];
heap[right]=temp;
reheap(2*index+1);

}

}

}

}

Add a comment
Know the answer?
Add Answer to:
// CMPS 390 // MinHeap.java // Complete 4 methods: getMin, add, removeMin, reheap public class MinHeap...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • a) Create a class MinHeap implementation using an Array. Find the kth smallest value in a...

    a) Create a class MinHeap implementation using an Array. Find the kth smallest value in a collection of n values, where 0 < k < n. Write a program that uses a minheap method to find the kth smallest value in a collection of n values. Use the MinHeap class defined in part a. public final class MinHeap<T extends Comparable<? super T>>              implements MinHeapInterface<T> {    private T[] heap;      // Array of heap entries; ignore heap[0]    private int...

  • add/ remove any methods to the program. please post new code and output Min Heap: public...

    add/ remove any methods to the program. please post new code and output Min Heap: public class MinHeap { private int[] Heap; private int size; private int maxsize; private static final int FRONT = 1; public MinHeap(int maxsize) { this.maxsize = maxsize; this.size = 0; Heap = new int[this.maxsize + 1]; Heap[0] = Integer.MIN_VALUE; } private int parent(int pos) { return pos / 2; } private int leftChild(int pos) { return (2 * pos); } private int rightChild(int pos) {...

  • JAVA Modify the existing (methods already in the file may be modified but not deleted) the...

    JAVA Modify the existing (methods already in the file may be modified but not deleted) the code to a MaxHeap and write a driver class to do the following: 1. Insert item into a Heap 2. Delete Max from the Heap 3. Display the Heap array 4. Convert an array to Heap 1,2 & 3 must all work on the same heap array. Option 4 is independent and must take in input from the user of an integer array and...

  • Check if an array is a heap in Java. Complete the method isHeapTree Together, these methods...

    Check if an array is a heap in Java. Complete the method isHeapTree Together, these methods are meant to determine if an array of objects corresponds to a heap. The methods are generic, and they should work with an array of any type T that implement Comparable<T>. Implement the second method so that it uses recursion to process the complete tree/subtree whose root is at position i in the array arr. The method should return true if that tree/subtree is...

  • Problem 2: based on java.util.LinkedList class, create MyStack class that should have the methods: push(), pop(),...

    Problem 2: based on java.util.LinkedList class, create MyStack class that should have the methods: push(), pop(), peek(), size(), isEmpty(). my linkedlist class is: public class Lab8_problem1 {    private Node head, tail; private int size;    public Lab8_problem1() { this.head = null; this.tail = null; this.size = 0; } //Insert a node at specifc Location public void insertAt(int value, int index) { Node newNode = new Node(); newNode.data = value; if(head == null){ head = newNode; tail = newNode; head.next...

  • Explain this java code, please. import java.util.Scanner; public class Program11 { public static void main(String[] args)...

    Explain this java code, please. import java.util.Scanner; public class Program11 { public static void main(String[] args) { Scanner stdIn = new Scanner(System.in); final int maxSize = 128; String[] titles = new String[maxSize]; int[] lengths = new int[maxSize]; int numDVDs = 0; String op; op = menu(stdIn); System.out.println(); while (!op.equalsIgnoreCase("q")) { if (op.equalsIgnoreCase("a")) { if (numDVDs < maxSize) numDVDs = addDVD(titles, lengths, numDVDs, stdIn); } else if (op.equalsIgnoreCase("t")) searchByTitle(titles, lengths, numDVDs, stdIn);    else if (op.equalsIgnoreCase("l")) searchByLength(titles, lengths, numDVDs, stdIn); System.out.println('\n');...

  • In this assignment, you will add several methods to the Binary Search Tree. You should have compl...

    In this assignment, you will add several methods to the Binary Search Tree. You should have completed the following three methods in the lab: public void insert(Key key, Value value) public Value get(Key key) public void inorder(Node root) For this assignment, you will implement the following: public void remove(Node root, Key key) public Key getMin(Node n) public Key getMax(Node n) public int height(Node n) The main method contains the statements to check whether your implementation works. You need to change...

  • 2. Write MinheapPriorityQueue constructor, which takes an array of data, and construct the max heap priority...

    2. Write MinheapPriorityQueue constructor, which takes an array of data, and construct the max heap priority queue using bottom-up algorithm. The expected run time should be O(n), where n is the total number of data. BubbleDown method is provided. You may test it in this minHeap public class MinHeapPriorityQueue<E extends Comparable<? super E>>{ private E data[]; private int size; public MinHeapPriorityQueue(){ this(100); } public MinHeapPriorityQueue(int cap){ size = 0; data = (E[]) new Comparable[cap]; } public MinHeapPriorityQueue(int[] a){ } public...

  • public class PQueue<E extends Comparable<E>> { private E[] elements; private int size; private int head; private...

    public class PQueue<E extends Comparable<E>> { private E[] elements; private int size; private int head; private int tail; Private int count;   } public void enqueue(E item) { if(isFull()){ return; } count++; elements[tail] = item; tail = (tail + 1) % size; } public E dequeue() { if(isEmpty()) return null; int ct = count-1; E cur = elements[head]; int index = 0; for(i=1;ct-->0;i++) { if(cur.compareTo(elements[head+i)%size])<0) cur = elements[(head+i)%size]; index = i; } } return remove((head+index%size); public E remove(int index) { E...

  • Create a program called GeneralizedBubbleSort that will make use of the Comparable Interface in the same...

    Create a program called GeneralizedBubbleSort that will make use of the Comparable Interface in the same way it is used in the GeneralizedSelectionSort. You should use the attached ComparableDemo to test your program. public class ComparableDemo { public static void main(String[] args) { Double[] d = new Double[10]; for (int i = 0; i < d.length; i++) d[i] = new Double(d.length - i); System.out.println("Before sorting:"); int i; for (i = 0; i < d.length; i++) System.out.print(d[i].doubleValue( ) + ", ");...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT