C# - Find the median of numbers in an array
C# - Find the median of numbers in an array
CODE
using System;
class Program
{
public static void Main()
{
int[] numbers = { 1, 3, 2, 5, 4, 6 };
//First sort the array
for (int i = 0; i < numbers.Length - 1; i++)
{
for (int j = i; j < numbers.Length; j++)
{
if (numbers[i] > numbers[j])
{
int temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
}
}
}
int length = numbers.Length;
double median;
//check if the length of the array is even or odd
if(length % 2 == 0)
{
//if even number, calculate the median as the average of the middle 2 elements
int midElement1 = numbers[(length - 1) / 2];
int midElement2 = numbers[length / 2];
median = (midElement1 + midElement2) / 2.0;
}
else
//if odd number, calculate the median as the middle element
median = numbers[length/2];
Console.WriteLine("Median = {0}", median);
//OUTPUT
//Median = 3.5
Console.ReadKey();
}
}
Comments
Post a Comment