Question

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 void add(E d) throws Exception{
      if (size >= data.length - 1) throw new Exception("Full");
      data[++size] = d;
      bubbleUp(size);
   }
   public E peek() throws Exception{
      if (size <= 0) throw new Exception("Empty");
      return data[1];
   }
   public E remove() throws Exception{
      if (size <= 0) throw new Exception("Empty");
      E ans = data[1];
      data[1] = data[size--];
      bubbleDown(1);
      return ans;
   }
   private void swap2(int i, int j){
      E temp = data[i];
      data[i] = data[j];
      data[j] = temp;
   }
   private void bubbleUp(int i){
      if (i <= 1) return;
      if (data[i].compareTo(data[i / 2]) >= 0) return;
      swap2(i, i / 2);
      bubbleUp(i / 2);
   }
   private void bubbleDown(int i){
      if ((i * 2) > size) return;
      int min_i = i * 2;
      if (min_i + 1 <= size) {
         if (data[min_i].compareTo(data[min_i + 1]) > 0)
            min_i += 1;
      }
      if (data[i].compareTo(data[min_i]) <= 0) return;
      swap2(i, min_i);
      bubbleDown(min_i);
   }
   public static void main(String[] args){
      int[] a = {3,2,7,5,1,6,4,8,9};
      try {
         long time, nextTime;
         time = System.nanoTime();
         MinHeapPriorityQueue minHeap = new MinHeapPriorityQueue(a.length + 1);
         for (int i = 0; i < a.length; ++i){
            minHeap.add(a[i]);
         }
         nextTime = System.nanoTime();
         System.out.println("\tTime used: " + (nextTime - time) + " nseconds");
         for (int i = 0; i < a.length; ++i){
            System.out.print(minHeap.remove() + ",");
         }
         System.out.println();
      }catch (Exception e){
         e.printStackTrace();
      }
      try {
         long time, nextTime;
         time = System.nanoTime();
         MinHeapPriorityQueue minHeap = new MinHeapPriorityQueue(a);
         nextTime = System.nanoTime();
         System.out.println("\tTime used: " + (nextTime - time) + " nseconds");
         for (int i = 0; i < a.length; ++i){
            System.out.print(minHeap.remove() + ",");
         }
         System.out.println();
      }catch (Exception e){
         e.printStackTrace();
      }
   }

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

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(E[] a) {

data = (E[]) new Comparable[a.length + 1];

for (int i = 0; i < a.length; ++i)

data[i + 1] = a[i];

size = a.length;

for (int i = 0; i <=a.length; i++) { // Start with the first

bubbleUp(i);

}

}

public void add(E d) throws Exception {

if (size >= data.length - 1)

throw new Exception("Full");

data[++size] = d;

bubbleUp(size);

}

public E peek() throws Exception {

if (size <= 0)

throw new Exception("Empty");

return data[1];

}

public E remove() throws Exception {

if (size <= 0)

throw new Exception("Empty");

E ans = data[1];

data[1] = data[size--];

bubbleDown(1);

return ans;

}

private void swap2(int i, int j) {

E temp = data[i];

data[i] = data[j];

data[j] = temp;

}

private void bubbleUp(int i) {

if (i <= 1)

return;

if (data[i].compareTo(data[i / 2]) >= 0)

return;

swap2(i, i / 2);

bubbleUp(i / 2);

}

private void bubbleDown(int i) {

if ((i * 2) > size)

return;

int min_i = i * 2;

if (min_i + 1 <= size) {

if (data[min_i].compareTo(data[min_i + 1]) > 0)

min_i += 1;

}

if (data[i].compareTo(data[min_i]) <= 0)

return;

swap2(i, min_i);

bubbleDown(min_i);

}

public static void main(String[] args) {

Integer[] a = { 3, 2, 7, 5, 1, 6, 4, 8, 9 };

try {

long time, nextTime;

time = System.nanoTime();

MinHeapPriorityQueue minHeap = new MinHeapPriorityQueue(a.length + 1);

for (int i = 0; i < a.length; ++i) {

minHeap.add(a[i]);

}

nextTime = System.nanoTime();

System.out.println("\tTime used: " + (nextTime - time) + " nseconds");

for (int i = 0; i < a.length; ++i) {

System.out.print(minHeap.remove() + ",");

}

System.out.println();

} catch (Exception e) {

e.printStackTrace();

}

try {

long time, nextTime;

time = System.nanoTime();

MinHeapPriorityQueue minHeap = new MinHeapPriorityQueue(a);

nextTime = System.nanoTime();

System.out.println("\tTime used: " + (nextTime - time) + " nseconds");

for (int i = 0; i < a.length; ++i) {

System.out.print(minHeap.remove() + ",");

}

System.out.println();

} catch (Exception e) {

e.printStackTrace();

}

}

}

====================================================
SEE OUTPUT

PLEASE COMMENT if there is any concern.

==============================

Add a comment
Know the answer?
Add Answer to:
2. Write MinheapPriorityQueue constructor, which takes an array of data, and construct the max heap priority...
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
  • Write merge method for mergeSort method, it takes the array of data, starting index of first...

    Write merge method for mergeSort method, it takes the array of data, starting index of first half, starting index of second half and end index of second half. please use the code below to test it public class A4Sort{ public static void mergeSort(int[] a, int l, int h){ if (l >= h) return; int mid = (h + l) / 2; mergeSort(a, l, mid); mergeSort(a, mid + 1, h); merge(a, l, mid + 1, h); } public static void main(String[]...

  • import java.util.Scanner; import class17.HeapPriorityQueue; import class17.PriorityQueue; /*************** * Homework D * * * Remove any initial...

    import java.util.Scanner; import class17.HeapPriorityQueue; import class17.PriorityQueue; /*************** * Homework D * * * Remove any initial package declaration that might be added to your file in * case you edit it in eclipse. * * The goal of the homework is to create two ArrayList based implementations of * a Priority Queue as explained in Section 9.2 (in 9.2.4 and 9.2.5) of the * textbook. * * These are to be made by completing the classes PQunsorted and PQsorted as...

  • 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) {...

  • iImplement a Singly Linked List detectLoop in Java, it would check whether the linked list contains...

    iImplement a Singly Linked List detectLoop in Java, it would check whether the linked list contains a loop. Print true if yes, false if not. Test by using the following code: LL<Integer> L = new LL<>(); for (int i = 1000; i > 0; i-=3) sl.add(i); try { L.insert(122, L.getNode(70), L.getNode(21)); if (L.detectLoop()) System.out.println("True"); else System.out.println("False."); } catch(Exception e){ e.printStackTrace(); } class Linkedlist<E>{ private static class Node<E>{ private E element; private Node<E> next; public Node(E e, Node<E> n){ element =...

  • using Data Structures using Java. Modify it to make the ADT resizable. For this ADT, the...

    using Data Structures using Java. Modify it to make the ADT resizable. For this ADT, the MAX_SIZE will not be final, but rather will be increased whenever an new item needs to be added and the array is full (ie. size==MAX_SIZE). Whenever the array needs to grow, add the lesser of: (i) half the current size, or; (ii) 50 additional. Have your ADT report its old and new maximum size whenever the resize operation is called by printing “ADT resized...

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

    Write MaxheapPriorityQueue constructor, which takes an array of data, and construct the max heap priority queue using bottom-up algorithm. Assuming bubbleDown method is provided. What is the best-case and worst-case of insertionSort? What is the best-case and worst-case of mergeSort? What is the best-case and worst-case of quickSort?

  • // CMPS 390 // MinHeap.java // Complete 4 methods: getMin, add, removeMin, reheap public class MinHeap...

    // CMPS 390 // MinHeap.java // Complete 4 methods: getMin, add, removeMin, reheap public class MinHeap { private Comparable a heap; // array of heap entries private static final int DEFAULT MAX SIZE = 100; private int lastIndex; // index of last entry public MinHeap() { heap = new Comparable (DEFAULT_MAX_SIZE]; lastIndex = 0; } // end default constructor public MinHeap (int maxSize) { heap = new Comparable (maxSize); lastIndex = 0; } // end constructor public MinHeap (Comparable[] entries)...

  • Write a unit test to test the following class. Using Java : //Test only the debit...

    Write a unit test to test the following class. Using Java : //Test only the debit method in the BankAccount. : import java.util.*; public class BankAccount { private String customerName; private double balance; private boolean frozen = false; private BankAccount() { } public BankAccount(String Name, double balance) { customerName = Name; this.balance = balance; } public String getCustomerName() { return customerName; } public double getBalance() { return balance; } public void setDebit(double amount) throws Exception { if (frozen) { throw...

  • Can anyone helps to create a Test.java for the following classes please? Where the Test.java will...

    Can anyone helps to create a Test.java for the following classes please? Where the Test.java will have a Scanner roster = new Scanner(new FileReader(“roster.txt”); will be needed in this main method to read the roster.txt. public interface List {    public int size();    public boolean isEmpty();    public Object get(int i) throws OutOfRangeException;    public void set(int i, Object e) throws OutOfRangeException;    public void add(int i, Object e) throws OutOfRangeException; public Object remove(int i) throws OutOfRangeException;    } public class ArrayList implements List {   ...

  • I am not passing some of the code when i run the testing . PriorityQueue public...

    I am not passing some of the code when i run the testing . PriorityQueue public class PriorityQueue<T extends Comparable<T>> implements IPriorityQueue<T> {    private Vector<T> theVector = new Vector<>(0, 1);    private int size = 0;    @Override    public void insert(T element) {        theVector.pushBack(element);        size++;        bubbleUp(); }    @Override    public T peekTop() throws java.util.NoSuchElementException {        if (isEmpty()) {            throw new java.util.NoSuchElementException();        }       ...

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
ADVERTISEMENT