Question

Create a java code that will take user input and find the median using two heaps...

Create a java code that will take user input and find the median using two heaps (max and min heap). The two heap must sort the elements from small to large. Running time must be efficient and below O(n^2). The algorithm must support the following methods:

- insert(b): insert a given element b in O(logn) time

- getMedian(): return the median in O(1) time

- removeMedian(): remove and return the median in O(logn) time

Note: The median will return the element that exist in the list, for example an even number of elements <9, 9, 1, 2> will return 2 instead of 5 which doesn't exist in the list.

Odd list exp <4, 8, 2> will return 4 (sorting <2,4,8>). Another even exp <15, -2, 10, -5, 11, 18, 5, 1> will return 5 (sorting <-5, -2, 1, 5, 10, 11, 15, 18>)

Answer with java or pseudo code and analyse the running time.

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

CODE

import java.util.Scanner;

import java.util.PriorityQueue;

import java.util.Collections;

// - We use 2 Heaps to keep track of median

// - We make sure that 1 of the following conditions is always true:

// 1) maxHeap.size() == minHeap.size()

// 2) maxHeap.size() - 1 = minHeap.size()

public class Main {

private static PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder()); // keeps track of the SMALL numbers

private static PriorityQueue<Integer> minHeap = new PriorityQueue<>(); // keeps track of the LARGE numbers

  

public static void main(String[] args) {

Scanner scan = new Scanner(System.in);

System.out.println("enter the number of integers: ");

int n = scan.nextInt();

for (int i = 1; i <= n; i++) {

System.out.println("Enter the number " + i + " : ");

insert(scan.nextInt());

}

scan.close();

  

System.out.println("The median is: " + getMedian());

System.out.println("Removing median: " + removeMedian());

}

  

private static void insert(int n) {

if (maxHeap.isEmpty()) {

maxHeap.add(n);

} else if (maxHeap.size() == minHeap.size()) {

if (n < minHeap.peek()) {

maxHeap.add(n);

} else {

minHeap.add(n);

maxHeap.add(minHeap.remove());

}

} else if (maxHeap.size() > minHeap.size()) {

if (n > maxHeap.peek()) {

minHeap.add(n);

} else {

maxHeap.add(n);

minHeap.add(maxHeap.remove());

}

}

// maxHeap will never have fewer elements than minHeap

}

  

private static double getMedian() {

if (maxHeap.isEmpty()) {

return 0;

}

return maxHeap.peek();

}

  

private static double removeMedian() {

if (maxHeap.isEmpty()) {

return 0;

}

return maxHeap.poll();

}

}

The complexity of median finding is O(N log N), as we need to read the stream, and due to heap insertions/deletions.

Add a comment
Know the answer?
Add Answer to:
Create a java code that will take user input and find the median using two heaps...
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
  • In class, we discussed the priority queue (PQ) ADT implemented using min-heap. In a min-heap, the...

    In class, we discussed the priority queue (PQ) ADT implemented using min-heap. In a min-heap, the element of the heap with the smallest key is the root of the binary tree. On the other hand, a max-heap has as root the element with the biggest key, and the relationship between the keys of a node and its parent is reversed of that of a min-heap. We also discussed an array-based implementation of heaps. In this assignment, your task is to...

  • in JAVA program.Use top-down design to design and implement a program to ask the user to...

    in JAVA program.Use top-down design to design and implement a program to ask the user to enter a list of integers, and then display to the user the mean and median of this list. You should first prompt the user to specify the length of the list of integers. For this assignment, your code should create an array of size 10, and then allow the user to specify the number of integers in their list, up to a maximum of...

  • Create a Java code that includes all the methods from the Lecture slides following the ADTs...

    Create a Java code that includes all the methods from the Lecture slides following the ADTs LECTURE SLIDE Collect/finish the Java code (interface and the complete working classes) from lecture slides for the following ADTS 2) ArrayList ADT that uses a linked list internally (call it LArrayList) Make sure you keep the same method names as in the slides (automatic testing will be performed)! For each method you develop, add comments and estimate the big-O running time of its algorithm....

  • for java: NOTE: Make sure, you have exception handling code in place for each exceptional condition...

    for java: NOTE: Make sure, you have exception handling code in place for each exceptional condition for every question. Also, make sure you have tested all the codes with various boundary conditions. Given a list of pairs; Give an efficient method (O(n)) to print all “Symmetric Pairs”. A pair is symmetric if both pair (i, j) and pair (j, i) exist in the list. For example, in { {3, 1}, {2, 6}, {3, 5}, {7, 4}, {5, 3}, {8, 7}...

  • Need help to answer this method in java Write a method int indexFirstOne(int[ ] input) The...

    Need help to answer this method in java Write a method int indexFirstOne(int[ ] input) The input array is sorted, and every element is 0 or 1. Return the index of the first 1. If there are no 1s in the array, return -1. The worst-case runtime must be O(logn)where n is the number of elements (no credits for slower runtimes) Example: a = [0,0,1,1,1]      return 2 a = [ 0,0,0,1]          return 3 a = [0,0,0]              return -1 int indexFirstOne...

  • C++ Question 9 5 pts Deleting the minimum element in a min-heap of N elements takes...

    C++ Question 9 5 pts Deleting the minimum element in a min-heap of N elements takes in average case O(N log N) O(1) O(N) Oſlog N) D Question 10 5 pts The time taken to find an element in an AVL tree of depth d is Old) 02) Oſlog d) Old log d) Question 11 5 pts Secondary clustering in a hash table occurs when using Linear probing Separate chaining Quadratic probing Double hashing Question 12 5 pts When sorting...

  • Create a Java code that includes all the methods from the Lecture slides following the ADTs...

    Create a Java code that includes all the methods from the Lecture slides following the ADTs LECTURE SLIDES Collect/finish the Java code (interface and the complete working classes) from lecture slides for the following ADTS: 4) Queue ADT that uses a linked list internally (call it LQueue) Make sure you keep the same method names as in the slides (automatic testing will be performed)! For each method you develop, add comments and estimate the big-O running time of its algorithm....

  • I need help In the lecture you got acquainted with the median algorithm, which calculates the median of an unsorted array with n∈N elements in O (n). But the algorithm can actually do much more: it is...

    I need help In the lecture you got acquainted with the median algorithm, which calculates the median of an unsorted array with n∈N elements in O (n). But the algorithm can actually do much more: it is not limited to finding only the median, but can generally find the ith element with 0≤i <n. Implement this generic version of the median algorithm by creating a class selector in the ads.set2.select package and implementing the following method: /** * Returns the...

  • JAVA For the code in which I implemented most of the quick select algorithm. Quick select...

    JAVA For the code in which I implemented most of the quick select algorithm. Quick select is a O(n) time algorithm to find the nth smallest value in an (unordered list). The following recursive algorithm finds thenth smallest element with an index bewtween left and right in list: Code: Integer QuickSelect(list, left, right, n) { if left = right // If we only have one index available return list[left] // return the element at that index endif pivotIndex ⇐ partition(list,...

  • PROGRAM DESCRIPTION Using the given class definitions for either C++, create a minimum heap that stores...

    PROGRAM DESCRIPTION Using the given class definitions for either C++, create a minimum heap that stores integers and and implements a minimum priority queue. (Your program can be "hard coded" for integers - it does not need to use templates, generics, or polymorphism.) Your data structure must always store its internal data as a heap. Your toString function should return a string with the heap values as a comma separated list, also including the size of the heap as well....

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