Write a program to find the median of the elements in an array. Median is the middle value in a sorted array. If there is an even number of elements in an array, then the median is mean of 2 middle values.
Sample Input and Output 1 :
Enter the number of elements in the array
5
Enter the elements in the array
2
4
1
3
5
The median of the array is 3.00
using System;
using System.Collections.Generic;
namespace App
{
class Program
{
public static void Main()
{
int i, j, n;
float median, temp;
Console.WriteLine("Enter the number of elements in the array");
n = int.Parse(Console.ReadLine());
float[] elements = new float[n];
Console.WriteLine("Enter the elements in the array");
for (i = 0; i < n; i++)
{
elements[i] = float.Parse(Console.ReadLine());
}
//sorting
for (i = 0; i < n - 1; i++)
{
for (j = 0; j < n - i - 1; j++)
{
if (elements[j] < elements[j + 1])
{
temp = elements[j];
elements[j] = elements[j + 1];
elements[j + 1] = temp;
}
}
}
//calculation median
if (n % 2 == 0)
{
median = (elements[(n / 2) - 1] + elements[(n / 2)]) / 2.0F;
}
else
{
median = elements[(n / 2)];
}
Console.WriteLine("The median of the array is {0}", median);
Console.ReadLine();
}
}
}
Comments
Leave a comment