Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

can someone please explain why my Java code is not printing the value shown in the picture. This is my code:import java.util.Collections; import java.util.PriorityQueue; import

can someone please explain why my Java code is not printing the value shown in the picture. This is my code:import java.util.Collections;
import java.util.PriorityQueue;
import java.util.Scanner;
public class Main {
static Scanner in;
//Method to calculate med of stream
public static void printMedian(int n)
{
// max heap to store the smaller half elements
PriorityQueuesmaller = new PriorityQueue<>
(Collections.reverseOrder());
// min-heap to store the greater half elements
PriorityQueue greater = new PriorityQueue<>();
int data = in.nextInt(); // first input
smaller.add(data);
double med = data; //first number itself a median
System.out.println(med);
for(int i=1; i greater.size()){
if(x < med)
{
greater.add(smaller.remove());
smaller.add(x);
}
else
greater.add(x);
med =(double)(smaller.peek()+greater.peek())/2;
}
// Case 2= both heaps are balanced
else if (smaller.size()== greater.size())
{
if (x < med)
{
smaller.add(x);
med =(double)smaller.peek();
}
else
{
greater.add(x);
med =(double)greater.peek();
}
}
// Case 3= the right side heap has more elements
else if (smaller.size()< greater.size())
if (x < med)
{
smaller.add(greater.remove());
greater.add(x);
}
else {
greater.add(x);
med =(double)(smaller.peek()+greater.peek())/2;
}
}
System.out.println(med);
}
//Driver code
public static void main(String[] args){
// TODO Auto-generated method stub
in = new Scanner(System.in); // Creates a Scanner object
int n = in.nextInt();
printMedian(n);
}
}

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

More Books

Students also viewed these Databases questions

Question

What is the best conclusion for Xbar Chart? UCL A X B C B A LCL

Answered: 1 week ago