Problem
I have a task that reads as follows:
Implement an IntegerList class with a Vector list object attribute that contains a collection of integers. Implement the findMedian () method which, for a given object from o of the IntegerList class, returns a number m from the vector o.list such that there are at least half of the numbers less than or equal to m, and the numbers greater than or equal to m are also at least half:
For example, for [1, 4, 1, 3, 5, 7] it will be the number 4, and for [1, 1, 1, 2, 2] it will be the number 1 and only 1. If the vector is empty then the method is supposed to throw an IllegalArgumentException exception.
What I tried?
import java.util.Vector; public class IntegerList { Vector<Integer> list =new Vector<Integer>(); public int findMedian(Vector<Integer>list){ if(list.size() ==0){ throw new IllegalArgumentException(); } int result =0; return result; } } public class Main { public static void main(String[] args){ IntegerList v = new IntegerList(); v.list.add(2); v.list.add(3); v.list.add(4); v.list.add(9); System.out.println(v.findMedian(v.list)); } }
My question:
Why this not working? What would you change to even better solve this problem?
Advertisement
Answer
It is working, but only on empty list. To make it work: we should apply what we learned ..and little try.
Voila:
public int findMedian(Vector<Integer> list) { if (list == null || list.isEmpty()) { throw new IllegalArgumentException("'list' is null or empty"); } // from here: list not null and list.size() > 0 ... : // sort the "list": java.util.Collections.sort(list); // if you may not modify the list: create a copy first! (the list remains sorted, also when leaving the method... // return "middle" element: return list.get(list.size()/2); }