Question

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 lastIndex; // Index of last entry and number of entries

   private boolean integrityOK = false;

private static final int DEFAULT_CAPACITY = 25;

private static final int MAX_CAPACITY = 10000;

...

}

/** An interface for the ADT minheap. */

public interface MinHeapInterface<T extends Comparable<? super T>>

{ // See Segment 24.33 for a commented version.

   public void add(T newEntry);

   public T removeMin();

   public T getMin();

   public boolean isEmpty();

   public int getSize();

   public void clear();

} // end MaxHeapInterface

0 0
Add a comment Improve this question Transcribed image text
Answer #1
import java.util.Arrays;

interface MinHeapInterface<T extends Comparable<? super T>>
{
    /** Adds a new entry to this heap.
    @param newEntry An object to be added. */
    public void add(T newEntry);
    
    /** Removes and returns the smallest item in this heap.
    @return Either the smallest object in the heap or,
    if the heap is empty before the operation, null. */
    public T removeMin();
    
    /** Retrieves the smallest item in this heap.
    @return Either the smallest object in the heap or,
    if the heap is empty, null. */
    public T getMin();
    
    /** Detects whether this heap is empty.
    @return True if the heap is empty, or false otherwise. */
    public boolean isEmpty();
    
    /** Gets the size of this heap.
    @return The number of entries currently in the heap. */
    public int getSize();
    
    /** Removes all entries from this heap. */
    public void clear();
} // end MinHeapInterface


public class MinHeap<K extends Comparable<K>> implements MinHeapInterface<K>{
    private static final int MAX_SIZE = 10;
    protected K[] array;
    protected int currentSize;

    /**
     * Constructs a new BinaryHeap.
     */
    @SuppressWarnings("unchecked")
    public MinHeap () {
        // In Java, we can not create a generics array, so we need to typecast it
        array = (K[])new Comparable[MAX_SIZE];  
        currentSize = 0;
    }

    /**
     * Constructs a new BinaryHeap.
     */
    @SuppressWarnings("unchecked")
    public MinHeap (K elements[]) {
        // In Java, we can not create a generics array, so we need to typecast it
        array = (K[])new Comparable[MAX_SIZE];  
        currentSize = 0;
        
        for(K e: elements) {
            add(e);
        }
    }

    @SuppressWarnings("unchecked")
    public void clear() {
        array = (K[])new Comparable[MAX_SIZE];  
        currentSize = 0;
    }
    
    /**
     * Add this element to the heap
     */
    public void add(K value) {
        // check if array need to be resized
        if (currentSize >= array.length - 1) {
            array = this.resize();
        }
        
        // place element into heap at the last position
        // and then we will check if minHeapify property is valid or not
        currentSize++;
        
        int index = currentSize;
        array[index] = value;
        
        heapifyupwards();
    }
    
    
    /**
     * Returns true if the heap has no elements; false otherwise.
     */
    public boolean isEmpty() {
        return currentSize == 0;
    }
    
    /**
     * Remove the min element from the heap and return it
     */
    public K removeMin() {
        if (this.isEmpty()) {
            throw new IllegalStateException();
        }
        // what do want return?
        K result = array[1];
        
        // move the last leaf node at root and root to the last leaf
        // then we will remove the last node and from new root
        // we will heapifyDownwards
        array[1] = array[currentSize];
        array[currentSize] = null;
        currentSize--;
        
        heapifyDownwards(1);
        
        return result;
    }
    
    public int getSize() {
        return currentSize;
    }
    
    public K getMin() {
        if(isEmpty()) {
            return null;
        }
        return array[1];
    }
    
    boolean remove(K key) {
        if (this.isEmpty()) {
            throw new IllegalStateException();
        }
        int index = -1;
        for(int i=0; i<currentSize; i++) {
            if(array[i].equals(key)) {
                index = i;
                break;
            }
        }
        
        if(index == -1) {
            return false;
        } else {
            array[0] = 
            array[index] = array[currentSize];
            array[currentSize] = null;
            currentSize--;
            heapifyDownwards(index);
            return true;
        }
        
    }
    
    /**
     * Performs the "bubble down" operation to place the element that is at the 
     * root of the heap in its correct place so that the heap maintains the 
     * min-heap order property.
     */
    protected void heapifyDownwards(int index) {
        
        // start from root, go to smaller of left and right node
        while (hasLeftChild(index)) {
            // which of my children is smaller?
            int smallerChild = leftIndex(index);
            if (hasRightChild(index)
                && array[leftIndex(index)].compareTo(array[rightIndex(index)]) > 0) {
                smallerChild = rightIndex(index);
            }
            
            // check if required to swap to maintain the heapify behavior 
            if (array[index].compareTo(array[smallerChild]) > 0) {
                swap(index, smallerChild);
            } else {
                break;
            }
            
            // go in into the tree where small child is present.
            index = smallerChild;
        }        
    }
    
    
    /**
     * This method starts from the last leaf node and recursively checks till
     * root, whether the entire tree is min-heapified or not
     */
    private void heapifyupwards() {
        int index = this.currentSize;
        
        while (hasParent(index)
                && (parent(index).compareTo(array[index]) > 0)) {
            // If parent/child are out of order; swap them
            swap(index, parentIndex(index));
            
            // in next iteration proceed with checking parent node
            // we will keep doing this till we reach root of tree
            index = parentIndex(index);
        }        
    }
    
    // this method is used to swap the values in the array at two given indices.
    private void swap(int index1, int index2) {
        K tmp = array[index1];
        array[index1] = array[index2];
        array[index2] = tmp;        
    }
        
    private boolean hasParent(int i) {
        return i > 1;
    }    
    
    private int leftIndex(int i) {
        return i * 2;
    }
        
    private int rightIndex(int i) {
        return i * 2 + 1;
    }
        
    private boolean hasLeftChild(int i) {
        return leftIndex(i) <= currentSize;
    }    
    
    private boolean hasRightChild(int i) {
        return rightIndex(i) <= currentSize;
    }
        
    private K parent(int i) {
        return array[parentIndex(i)];
    }    
    
    private int parentIndex(int i) {
        return i / 2;
    }
    
    private K[] resize() {
        // this method basically creates another array, which is of double capacity
        // it also restores the elements which are already present.
        return Arrays.copyOf(array, array.length * 2);
    }
    
    
    public static void main(String args[]) {
        MinHeap<Integer> data = new MinHeap<>();
        
        for(int i=0; i<100; i++) {
            data.add((int) (Math.random() * 1000));
        }
        
        int count = 0;
        int k = 10;
        int result = 0;
        while(count < k) {
            result = data.removeMin();
            count++;
        }
        System.out.println(k + "th element: " + result);
    }
}
Add a comment
Know the answer?
Add Answer to:
a) Create a class MinHeap implementation using an Array. Find the kth smallest value in a...
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
  • // 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)...

  • Can someone help me with the main class of my code. Here is the assignment notes....

    Can someone help me with the main class of my code. Here is the assignment notes. Implement project assignment �1� at the end of chapter 18 on page 545 in the textbook. Use the definition shown below for the "jumpSearch" method of the SkipSearch class. Notice that the method is delcared static. Therefore, you do not need to create a new instance of the object before the method is called. Simply use "SkipSearch.jumpSearch(...)" with the appropriate 4 parameter values. When...

  • Suppose that you have several numbered billiard balls on a pool table. The smallest possible number...

    Suppose that you have several numbered billiard balls on a pool table. The smallest possible number on the ball is “1”. At each step, you remove a billiard ball from the table. If the ball removed is numbered n, you replace it with n balls randomly numbered less than n. For example, if you remove the “5” ball, you replace it with balls numbered “2”, “1”, “1”, “4”, and “3”, where numbers 2, 1, 1, 4, and 3 were randomly...

  • Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored in an ...

    Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored in an array. Implement all methods in ArrayStack class using resizable array strategy, i.e. usedoubleArray() Must throw StackException during exception events in methods:    peek(), pop(), ArrayStack(int initialCapacity) Do not change or add data fields Do not add new methods */ import java.util.Arrays; public class Arraystack«Т> implements Stack!nterface«T> private TI stack;// Array of stack entries private int topIndex; /7 Index of top entry private static...

  • Write a second constructor that could be added to the HeapPriorityQueue class. This constructor accepts an...

    Write a second constructor that could be added to the HeapPriorityQueue class. This constructor accepts an array of elements as a parameter and uses that array as the heap rather than creating a new array. Of course, the array passed in is probably not in proper heap ordering, so you must rearrange it until it is. There's a neat trick for achieving this: If you just "bubble down" all of the non-leaf nodes of the heap, starting from the last...

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

  • java The following code is an implementation of a HeapPriorityQueue. You are to implement the methods...

    java The following code is an implementation of a HeapPriorityQueue. You are to implement the methods commented with: // TODO: TIP: Do not just go from memory of your assignment implementation, be sure to consider carefully the constructor and method implementation provided to you. NOTE: You do not have to provide an implementation for any methods intentionally omitted public class Heap PriorityQueue implements PriorityQueue private final static int DEFAULT SIZE 10000 private Comparable [ ] storage private int currentSize: public...

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

  • Load to the IDEA the remaining classes from the provided Lab02.zip file. Repeat the previous project...

    Load to the IDEA the remaining classes from the provided Lab02.zip file. Repeat the previous project inside the ArraySetWithArray class. As shown in the UML diagram below ArraySetWithArray class does not utilize ResizableArrayBag object as its instance variable, it has setOfEntries defined as an array which should be dynamically resized if more room needed (double the size). displaySet method should check if the set is empty and display appropriate message; if the set is not empty should display the number...

  • Java Write an intersection method for the ResizableArrayBag class. The intersection of two bags is the...

    Java Write an intersection method for the ResizableArrayBag class. The intersection of two bags is the overlapping content of the bags. Intersections are explained in more detail in Chapter 1, #6. An intersecion might contain duplicates. The method should not alter either bag. The current bag and the bag sent in as a parameter should be the same when the method ends. The method header is: public BagInterface<T> intersection(ResizableArrayBag <T> anotherBag) Example: bag1 contains (1, 2, 2, 3) bag2 contains...

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