In: Computer Science
Complete the following method in java:
public static List<Integer> runningMedianOfThree(List items)
Create and return a new List<Integer> instance (of any subtype of List of your choice) whose first two elements are the same as that of original items, after which each element equals the median of the three elements in the original list ending in that position. For example, when called with a list that prints out as [5, 2, 9, 1, 7, 4, 6, 3, 8], this method would return an object of type List<Integer> that prints out as [5, 2, 5, 2, 7, 4, 6, 4, 6].
Java Program:
import java.util.*;
class MedianList
{
//Main method
public static void main(String args[])
{
//Creating original list
List<Integer> orgLst = new
ArrayList<Integer>();
//Adding elements
orgLst.add(5);
orgLst.add(2);
orgLst.add(9);
orgLst.add(1);
orgLst.add(7);
orgLst.add(4);
orgLst.add(6);
orgLst.add(3);
orgLst.add(8);
System.out.print("\nOriginal List:
");
//ITerating and printing
elements
for(Integer a:orgLst)
{
System.out.print(a + " ");
}
//Calling function
List<Integer> retLst =
runningMedianOfThree(orgLst);
System.out.print("\n\nList after
calculating median: ");
//ITerating and printing
elements
for(Integer a:retLst)
{
System.out.print(a + " ");
}
}
//Method that finds the median of three
values
public static List<Integer>
runningMedianOfThree(List<Integer> items)
{
//Creating a new list
List<Integer> retLst = new
ArrayList<Integer>();
//Adding first two elements
retLst.add(items.get(0));
retLst.add(items.get(1));
int median;
//Iterating from third
elements
for(int i=2; i<items.size();
i++)
{
//Calculating
median
if
((items.get(i-2) > items.get(i-1)) != (items.get(i-2) >
items.get(i)))
{
median = items.get(i-2);
}
else if
((items.get(i-1) > items.get(i-2)) != (items.get(i-1) >
items.get(i)))
{
median = items.get(i-1);
}
else
{
median = items.get(i);
}
//Adding median
value
retLst.add(median);
}
//Returning new list
return retLst;
}
}
___________________________________________________________________________________________________________________
Sample Run: