Need help writing this in Java You can test your code by changing your IntLister
ID: 3817035 • Letter: N
Question
Need help writing this in Java
You can test your code by changing your IntLister to use an IntListSorted instance instead of an IntList.
You see that your new IntListSorted can find the minimum and maximum values in the list in a much simpler and faster way than the superclass can. Override these methods with this faster approach. Modify your IntListTester class to use an IntListSorted instance instead of an IntList and try it out.
Besides overriding superclass functionality, subclasses can add functionality not available to the superclass. Write a method getMedian that returns the middle element of a sorted list. (Note: When the list contains an even number of items, just return the last element in the first half of the list, i.e., the element right before the "center" of the list. For example, in the case of [0, 1, 3, 10], 1 should be returned.) Demonstrate your code by adding additional statements to IntListTester.
Explanation / Answer
Answer:
public class IntListSorted
extends IntList
{
public IntListSorted()
{
super();
}
/** * Adds the new item not at end of the list, but at the correct spot so that * the list stays sorted. *
* @param newItem the item to add.
*/
public void add(int newItem)
{
// Ask the superclass to insert the item at the end of the list. super.add(newItem);
// Now, look at the item right before the new item. Is it greater than // the new item? If so, swap the items. Keep doing this until we either
// see an item before the new item that is not greater or we hit the
// front of the list.
int tmp;
for (int i = size - 1; i > 0 && list[i - 1] > list[i]; --i)
{
tmp = list[i];
list[i] = list[i - 1];
list[i - 1] = tmp;
}
}
@Override
public int getMinimum()
{
return list[0];
}
@Override
public int getMaximum()
{
return list[list.length - 1];
}
public int getMedian()
{
if(list.length % 2 == 0)
return list[list.length/2];
return list[(list.length/2) + 1];
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.