Using C#, create a function/subroutine that takes two arrays as parameters, and return the median of the two arrays.
Example of Median values of two arrays
- Example I:
Input: arr1 = {4, 3 }, arr2 = { 4, 1, 7 }
Output: 4 - Example II:
Input: arr1 = {4, 3 }, arr2 = { 4, 1 }
Output: 3.5
What is the median value?
The median value of a list of numbers is the number that is right in the middle of this list. The list must be sorted to get the median.
Assume we have the following list of numbers
1 , 2 , 5 , 4 , 1
First, we need to sort the list:
1 , 1 , 2 , 4 , 5
The median of the list above is 2, which falls in the middle of the list.
The median value of an even List
But what we have a list with even numbers? The median, in this case, is the sum of the two numbers that fall in the middle of the list, divided by 2.
For example, given the sorted list below
1 , 1 , 2 , 4 , 5 , 7
The two numbers that fall in the middle are 2 and 4
Thus, the median is (2+4) / 2 = 3
Solutions:
double CalculateMedian(int[] num1, int[] num2) { // Initialize variables int lenght1 = num1.Length; int lenght2 = num2.Length; double median; // Initialize new array int[] mergedArr = new int[lenght1 + lenght2]; // Merge the two arrays into the new one for (int i = 0; i < lenght1 + lenght2; i++) { if (i < lenght1) { mergedArr[i] = num1[i]; } else { int newLength = i - lenght1; mergedArr[i] = num2[newLength]; } } // Sort the Array Array.Sort(mergedArr); // Calculate the median for an even list of numbers if (mergedArr.Length % 2 == 0) { int medianIndex1 = mergedArr.Length / 2; int medianIndex2 = mergedArr.Length / 2 + 1; int number1 = mergedArr[medianIndex1 - 1]; int number2 = mergedArr[medianIndex2 - 1]; median = (number1 + number2) / 2.00; } else // Calculate the media for odd List of numbers { int medianIndex = ((mergedArr.Length - 1) / 2) + 1; median = mergedArr[medianIndex - 1]; } return median; }
Call the Function
int[] arr1 = { 4, 3 }; int[] arr2 = { 4, 1, 7 }; double median = CalculateMedian(arr1, arr2); Console.WriteLine("The median is: " + median);