assignment part b For this assignment, you will be creating a method which will
ID: 3703075 • Letter: A
Question
assignment part b
For this assignment, you will be creating a method which will be used later in the project.
Write a method named median:
Write a method named median which calculate, and return, the median of an array of integers. The method should receive as parameters, an array of integers and the filled size of the array.
Your method should assume that the array will contain some positive integers, filled in ascending order. This is a partially-filled array, where the number of items in the array may be less than the declared size of the array. The size parameter tells the method how many items are actually stored in the array.
The median should be calculated as a double value, as follows:
If there are an odd number of integers in the array, then the median is defined as the integer stored in the middle array position.
If there are an even number number of integers in the array, then the median is defined as the average of the integers stored in the two middle array positions.
Starter Code:
public class CalculateMedian {
/**
* Calculates the median of the integers in array 'list'
* @param list The array containing the integers for which to calculate the median
* @param size The number of integers in array 'list'
* @return The median of the integers in the array
*/
public static double median(int [] list, int size) {
return 0;
}
}
Explanation / Answer
CalculateMedian.java
public class CalculateMedian {
/**
* Calculates the median of the integers in array 'list'
* @param list The array containing the integers for which to calculate the median
* @param size The number of integers in array 'list'
* @return The median of the integers in the array
*/
public static double median(int [] list, int size) {
if(size % 2 != 0){
return list[size/2];
}
else{
return (list[size/2] + list[(size-1)/2])/2;
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.