You are given an unsorted array x of elements that implement the Comparable inte
ID: 3686153 • Letter: Y
Question
You are given an unsorted array x of elements that implement the Comparable interface. There are no duplicates in this array . You are also given a variable m of type Comparable. Write the code needed to assign to m a reference to the median value of the array . (You may modify the array x by rearranging its elements .) NOTE: The median of a set of values is the value in the set such that there are as many values that are greater as there are that are less. For purposes of THIS exercise, if the array has an even number of members, the median is the greater of the two middle values . EXAMPLE 1: Given "bob" "carol" "ted" "alice" "fred" the median is "carol" because there are "bob" and "alice" are less than "carol" and "fred" and "ted" are greater. EXAMPLE 2: Given "bob" "carol" "ted" "alice" "fred" "sue", the middle two values are "carol" and "fred" and so in THIS exercise we would consider the greater to be the median.
Explanation / Answer
import java.util.Arrays;
public class MedianArray {
public static void main(String args[]) {
// Create array of four Item objects.
Element[] items = new Element[5];
items[0] = new Element("bob");
items[1] = new Element("carol");
items[2] = new Element("ted");
items[3] = new Element("alice");
items[4] = new Element("fred");
Element med = getMedian(items);
System.out.println(" Median: "+med.value);
items = new Element[6];
items[0] = new Element("bob");
items[1] = new Element("carol");
items[2] = new Element("ted");
items[3] = new Element("alice");
items[4] = new Element("fred");
items[5] = new Element("sue");
med = getMedian(items);
System.out.println(" Median: "+med.value);
}
public static Element getMedian(Element items[]) {
// Sort the Items with their Comparable interface methods.
Arrays.sort(items);
// Display sorted results.
for (Element element : items) {
System.out.println(element);
}
if(items.length %2 != 0)
return (items[items.length/2+1]);
else {
int center = items.length/2;
return items[center].compareTo(items[center-1]) < 1 ? items[center] : items[center-1];
}
}
}
class Element implements Comparable<Element> {
public String value;
public Element(String value) {
this.value = value;
}
public int compareTo(Element item) {
// Compare both value fields.
return this.value.compareToIgnoreCase(item.value);
}
public String toString() {
return "Value = " + value;
}
}
------------output-----------D: aviChegjava>java MedianArray
Value = alice
Value = bob
Value = carol
Value = fred
Value = ted
Median: fred
Value = alice
Value = bob
Value = carol
Value = fred
Value = sue
Value = ted
Median: carol
--------
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.