Write a Program to Find the Median of Array (by Sorting)

Write a Program to Find the Median of Array (by Sorting)

Explanation

You will be given a list of numbers.

Let's say 7, 8, 4, 5, 2

First, you have to sort the numbers using the swapping methodology.

Sorted list: 2, 4, 5, 7, 8

To write a program to find the median of array, first, find the total number of elements in the list and based on that apply the median formula to calculate the median.

This question was asked in the Zoho interview.

Algorithm

  1. Start the program
  2. Define a matrix variable
  3. Get the list of elements as the input
  4. Sort all the elements using swapping methodology by comparing one element a[i] with a[i+1] and a[i+2]. You can use any other sorting algorithms.
  5. If the number of elements is even use median=(a[n/2]+a[n/2+1])/2.0 this formula to find the median else use median=a[n/2+1]
  6. Print the median and the sorted list
  7. Stop the program

C/C++ Program

Prerequisites:

Code:

You can execute this program using our CSEstack online IDE.

#include<stdio.h>
#define N 10

int main()
{
  int i, j, n;
  float median, a[N], t;

  printf("Enter the number of items"); 
  scanf("%d", &n);

  printf("\nInput %d values", n); 
  for(i=1; i<=n; i++) 
    scanf("%f", &a[i]);

  for(i=1; i<=n-1; i++)
  {
    for(j=1; j<=n-1; j++)
    {
      if(a[j]<=a[j+1]) {
        t=a[j]; a[j]=a[j+1]; a[j+1]=t;
      }
      else {
          continue;
      }
   }
  }

  if(n%2 == 0)
    median=(a[n/2]+a[n/2+1])/2.0; 

  else
    median=a[n/2+1]; 

  for(i=1; i<=n; i++) 
    printf(" %f", a[i]);

  printf("\nMedian is %f", median);

  return 0;
}

Output:

Enter the number of items
5

Input 5 values 
11.000000 8.500000 7.500000 4.554000 2.400000

Median is 7.500000

Just like any for loop, you can also use the while or do-while loop to solve this problem.

Other related question asked in Zoho interview: Find transpose of matrix.

You can also this program to find the median of array in any other programming language as C/C++, Java or Python. Give it a try.

Leave a Reply

Your email address will not be published. Required fields are marked *