# Program : Find the median of an array.

**Explanation :** The median of an array is the middle element when the array is sorted in ascending order. In other words, it is the value that divides the array into two equal halves. To find the median, you first need to sort the array in non-decreasing order. If the size of the array is odd, then the median is the value at the middle index. If the size is even, then the median is the average of the two middle values.

Let’s take an example to illustrate this:

Consider the array [5, 9, 2, 7, 3, 6, 8].

First, we sort the array in non-decreasing order: [2, 3, 5, 6, 7, 8, 9].

Since the size of the array is odd (7), the median is the value at the middle index, which is 6. Therefore, 6 is the median of the given array.

The median is a useful measure of the central tendency of a dataset. It represents the value around which the data points are centered. It is especially valuable when dealing with data that may contain outliers, as it is less affected by extreme values compared to other measures like the mean.

## Solution :

#include <iostream> using namespace std; double findMedian(int array[], int size) { int i, j, temp; // Sort the array using bubble sort for (i = 0; i < size - 1; i++) { for (j = 0; j < size - i - 1; j++) { if (array[j] > array[j + 1]) { temp=array[j]; array[j]=array[j + 1]; array[j+1]=temp; } } } // Calculate the median if (size % 2 == 0) { return (array[size / 2 - 1] + array[size / 2]) / 2.0; } else { return array[size / 2]; } } int main() { const int MAX_SIZE = 100; int size, i; int arr[MAX_SIZE]; double median; cout << "Enter the size of the array: "; cin >> size; cout << "Enter the elements of the array: "; for (i = 0; i < size; i++) { cin >> arr[i]; } median = findMedian(arr, size); cout << "The median of the array is: " << median; return 0; }

## Output :

Enter the size of the array: 7 Enter the elements of the array: 5 9 2 7 3 6 8 The median of the array is: 6

Want to practice more problems involving Array 1-D ? Click here.