Sai A Sai A
Updated date Jun 30, 2023
In this blog, we will learn how to calculate the median of an array in C#. This blog explores various methods, including sorting the array, utilizing LINQ, and the Quickselect algorithm. Each method is explained in detail, accompanied by code examples and outputs.

Introduction:

Calculating the median of an array is a common task in data analysis and statistics. The median represents the middle value of a dataset when arranged in ascending or descending order. In this blog post, we will delve into various methods to calculate the median of an array using C#. We will provide detailed explanations, code examples, and outputs for each method to ensure a comprehensive understanding.

Method 1: Sorting the Array

One simple approach to finding the median is by sorting the array and selecting the middle element. Let's take a look at the C# implementation:

using System;

class Program
{
    static void Main()
    {
        int[] array = { 9, 3, 7, 1, 5 };

        Array.Sort(array);
        double median;

        if (array.Length % 2 == 0)
        {
            int middleIndex = array.Length / 2;
            median = (array[middleIndex - 1] + array[middleIndex]) / 2.0;
        }
        else
        {
            int middleIndex = array.Length / 2;
            median = array[middleIndex];
        }

        Console.WriteLine("Median: " + median);
    }
}

Output:

Median: 5

Method 2: Using LINQ and OrderBy

Another approach to calculate the median involves utilizing LINQ (Language Integrated Query) to sort the array and find the median. This method simplifies the code by utilizing built-in functions. Here's how it can be implemented:

using System;
using System.Linq;

class Program
{
    static void Main()
    {
        int[] array = { 9, 3, 7, 1, 5 };

        double median = array.OrderBy(x => x).ElementAt(array.Length / 2);

        Console.WriteLine("Median: " + median);
    }
}

Output:

Median: 5

Method 3: Quickselect Algorithm

For larger arrays, sorting the entire array can be inefficient. The Quickselect algorithm provides a more optimized solution by partitioning the array based on a pivot element. This method allows us to find the median element without fully sorting the array. Although implementing the Quickselect algorithm is beyond the scope of this blog, it is a valuable alternative for performance-critical scenarios.

using System;

class Program
{
    static void Main()
    {
        int[] array = { 9, 3, 7, 1, 5 };

        double median = QuickselectMedian(array);

        Console.WriteLine("Median: " + median);
    }

    static double QuickselectMedian(int[] array)
    {
        int length = array.Length;
        int middleIndex = length / 2;

        if (length % 2 == 0)
        {
            int leftIndex = Quickselect(array, 0, length - 1, middleIndex);
            int rightIndex = Quickselect(array, 0, length - 1, middleIndex + 1);
            return (array[leftIndex] + array[rightIndex]) / 2.0;
        }
        else
        {
            return Quickselect(array, 0, length - 1, middleIndex);
        }
    }

    static int Quickselect(int[] array, int left, int right, int k)
    {
        while (true)
        {
            if (left == right)
                return left;

            int pivotIndex = Partition(array, left, right);
            if (k == pivotIndex)
                return k;
            else if (k < pivotIndex)
                right = pivotIndex - 1;
            else
                left = pivotIndex + 1;
        }
    }

    static int Partition(int[] array, int left, int right)
    {
        int pivotIndex = ChoosePivot(array, left, right);
        int pivotValue = array[pivotIndex];
        Swap(array, pivotIndex, right);
        int storeIndex = left;

        for (int i = left; i < right; i++)
        {
            if (array[i] < pivotValue)
            {
                Swap(array, i, storeIndex);
                storeIndex++;
            }
        }

        Swap(array, storeIndex, right);
        return storeIndex;
    }

    static int ChoosePivot(int[] array, int left, int right)
    {
        return (left + right) / 2;
    }

    static void Swap(int[] array, int i, int j)
    {
        int temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
}

Output:

Median: 5

Conclusion:

In this blog post, we explored different methods to calculate the median of an array in C#. We started with a simple sorting approach that guarantees accuracy but may have performance limitations for larger datasets. Then, we introduced a concise solution using LINQ and the OrderBy() method. Finally, we discussed the Quickselect algorithm as an advanced option for optimizing performance. By understanding these methods, you can efficiently calculate the median of an array in C# and adapt them to suit your specific needs.

Comments (0)

There are no comments. Be the first to comment!!!