Horje
How to Find Median of Numbers in an Array in C?

The median of an array is defined as the middle element if the array size is odd, or the average of the two middle elements if the array size is even, when an array is sorted. In this article, we will learn how to find the median of numbers in an array in C.

Example

Input:
myArray: {1, 2, 3, 4, 5, 6}

Output:
The Median of the Array is : 3.50

Finding Median in an Array of Integers in C

To find the median of numbers in an array in C, we will first sort the array in ascending order using the qsort() function. The median of an array is determined by its size. If the array has an odd number of elements, the median will be the middle element after sorting the array. However, if the array has an even number of elements, the median will be the average of the two middle elements once the array is sorted.

C Program to Find the Median of a Sorted Array

The below program demonstrates how we can find the median of numbers in an array in C.

C
// C program to Find the Median of Numbers in an Array

#include <stdio.h>
#include <stdlib.h>

// Comparison function for qsort
int compare(const void* a, const void* b)
{
    return (*(int*)a - *(int*)b);
}

// Function to find the median of the array
float medianFn(int arr[], int size)
{
    // Sort the array in ascending order
    qsort(arr, size, sizeof(int), compare);

    // If the size of the array is even, return the average
    // of the two middle elements
    if (size % 2 == 0) {
        return (arr[size / 2 - 1] + arr[size / 2]) / 2.0;
    }
    // If the size is odd, return the middle element
    // directly
    else {
        return arr[size / 2];
    }
}

int main()
{
    // Declare an array
    int myArray[] = { 1, 2, 3, 4, 5, 6 };
    // Find the size of the array
    int size = sizeof(myArray) / sizeof(myArray[0]);

    // Find the median of the sorted array
    float median = medianFn(myArray, size);
    printf("The Median of the Array is : %.2f\n", median);

    return 0;
}

Output
The Median of the Array is : 3.50

Time Complexity: O(n log n), here n denotes the total number of elements in the array.
Auxiliary Space: O(1)




Reffered: https://www.geeksforgeeks.org


C Language

Related
C Program to Implement Singly Linked List C Program to Implement Singly Linked List
Implementation of Graph in C Implementation of Graph in C
C Program to Implement AVL Tree C Program to Implement AVL Tree
How to Release Memory in C? How to Release Memory in C?
How to Read From a File in C? How to Read From a File in C?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
17