Write a function called median that returns the median entry in a 1-dimensional
ID: 3575283 • Letter: W
Question
Write a function called median that returns the median entry in a 1-dimensional array of integers. For example, if we have an array a={3,4,5,1,6}; then the median entry of this array a is 4.
If the array size is even, it means that array has even number of elements. For example, a={3,2,4,1}, then first sort it, a becomes {1,2,3,4}, then the median entry will be the average of 2 and 3, which is 2.5.
a. First ouput should have you sort the array a first
b. then second output find the entry in the middle position.
Explanation / Answer
Program:
public class calcMedian {
public static void main(String[] args) {
// TODO Auto-generated method stub
int intArray[]={1,2,5,6,2,23,2};
int sortedArray[]=sort(intArray);
System.out.print("Sorted array: ");
for(int i=0;i<sortedArray.length;i++){
System.out.print(sortedArray[i] + " ");
}
float medianValue=median(sortedArray);
System.out.println(" Median value is: " + medianValue);
}
static float median(int arr[]){
//returns median value
if(arr.length%2==0){
return ((float) arr[arr.length/2 -1]+arr[arr.length/2 ])/2 ;
}
else{
return arr[arr.length/2];
}
}
static int[] sort(int arr[]){
//returns sorted array
int temp;
for(int i=0;i<arr.length;i++){
for(int j=i+1;j<arr.length;j++){
if(arr[j]<arr[i]){
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
return arr;
}
}
Sample run:
1) when array is {1,2,5,6,2,23,2} :
Sorted array: 1 2 2 2 5 6 23
Median value is: 2.0
2) when array is {1,2,5,6,2,23}:
Sorted array: 1 2 2 5 6 23
Median value is: 3.5
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.