Java: Find the median of the number inside the window
Median in Sliding Window
Write a Java program to find the median of the numbers inside the window (size k) at each step in a given array of integers with duplicate numbers. Move the window to the array start.
{|1, 2, 3|, 4, 5, 6, 7, 8, 8} -> Return median 2
{1, |2, 3, 4|, 5, 6, 7, 8, 8} -> Return median 3
{1, 2, |3, 4, 5|, 6, 7, 8, 8} -> Return median 4
{1, 2, 3, |4, 5, 6|, 7, 8, 8} -> Return median 5
{1, 2, 3, 4, |5, 6, 7|, 8, 8} -> Return median 6
{1, 2, 3, 4, 5, |6, 7, 8|, 8} -> Return median 7
{1, 2, 3, 4, 5, 6, |7, 8, 8|} -> Return median 8
Result array {2, 3, 4, 5, 6, 7, 8}
Sample Solution:
Java Code:
Sample Output:
Original array: [1, 2, 3, 4, 5, 6, 7, 8, 8] Value of k: 3 Result: 2 3 4 5 6 7 8
Pictorial Presentation:
Flowchart:
For more Practice: Solve these Related Problems:
- Write a Java program to compute the average of numbers in each sliding window of a given size in an array.
- Write a Java program to calculate the sum of elements in every sliding window of size k in an array.
- Write a Java program to determine the mode (most frequent element) within each sliding window of an array.
- Write a Java program to find the minimum element in each sliding window of a given array.
Go to:
PREV : Elements Smaller Than Another Array.
NEXT : Max in Sliding Window.
Java Code Editor:
Company: Google
Contribute your code and comments through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.