calculate median

Calculating the Median in C

To calculate the median in C, you can follow these steps:

  1. Sort the array: Start by sorting the array in ascending order. This is necessary to find the middle value(s) in the array.

  2. Determine the middle index: Check if the length of the array is odd or even. If it is odd, the middle index is simply the length of the array divided by 2 (integer division). If it is even, there are two middle indices: length of the array divided by 2 and length of the array divided by 2 minus 1.

  3. Calculate the median: If the length of the array is odd, the median is the value at the middle index. If the length of the array is even, the median is the average of the values at the two middle indices.

Here's an example implementation of a function that calculates the median of an array in C:

#include <stdio.h>

float calculateMedian(int arr[], int length) {
    // Sort the array
    for (int i = 0; i < length - 1; i++) {
        for (int j = 0; j < length - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }

    // Calculate the median
    if (length % 2 == 1) {
        return arr[length / 2];
    } else {
        int middle1 = length / 2;
        int middle2 = middle1 - 1;
        return (arr[middle1] + arr[middle2]) / 2.0;
    }
}

int main() {
    int arr[] = {5, 2, 9, 1, 7, 6};
    int length = sizeof(arr) / sizeof(arr[0]);

    float median = calculateMedian(arr, length);
    printf("The median is: %.2f\n", median);

    return 0;
}

In this example, we have an array arr with values {5, 2, 9, 1, 7, 6}. The calculateMedian function sorts the array using the bubble sort algorithm and then calculates the median based on the sorted array. The main function demonstrates how to use the calculateMedian function and prints the result.

Please note that this is just one way to calculate the median in C, and there are other algorithms and approaches that can be used as well.