Question: Solve using JAVA Problem 1 (5 pts): simpleSelect method Problem 2 (20 pts): buildHeap method Problem 3 (15 pts): removeMax method Problem 4 (5 pts):
Solve using JAVA
Problem 1 (5 pts): simpleSelect method
Problem 2 (20 pts): buildHeap method
Problem 3 (15 pts): removeMax method
Problem 4 (5 pts): heapSelect method
Below are the missing codes:
public class BinaryHeap { private Word[] wordArray; private int size; public BinaryHeap(Word[] array){ size = array.length; buildHeap(array); } // Problem #2 (20 pts) // Fill in the following method with an O(n) time algorithm // that builds an n element complete binary heap. // Note: You are allowed to add helper methods. public void buildHeap(Word[] array){ } // Problem #3 (15 pts) // Fill in the following method with an O(log(n)) time algorithm // that removes the root element, restores the heap structure, // and finally returns the removed root element. public Word removeMax(){ return null; } }
public class Selector { private static void swap(Word[] array, int i, int j){ if(i == j) return; Word temp = array[i]; array[i] = array[j]; array[j] = temp; } // Problem #1 (5 pts) // Fill in the following method with an O(n*k) time algorithm // that returns the k largest elements of array in order from // largest to smallest. // Note: This should return an array with k elements. // Hint: Your approach should be similar to selection sort. public static Word[] simpleSelect(Word[] array, int k){ return null; } // Problem #4 (5 pts) // Fill in the following method with an O(n + klog(n)) time algorithm // that returns the k largest elements of array in order from // largest to smallest. // Note: This should return an array with k elements. // Hint: Your approach should use a BinaryHeap. public static Word[] heapSelect(Word[] array, int k){ return null; } }
import java.util.Arrays; public class Main { public static void main(String[] args){ // Testing Selection Approach Word[] wordArray1 = WordReader.loadWords(); Word[] mostFrequent1 = Selector.simpleSelect(wordArray1, 500); System.out.println("mostFrequent1: " + Arrays.toString(mostFrequent1)); // Testing Heap-based Approach Word[] wordArray2 = WordReader.loadWords(); Word[] mostFrequent2 = Selector.heapSelect(wordArray2, 500); System.out.println("mostFrequent2: " + Arrays.toString(mostFrequent2)); } }
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
