Search code examples
arraysif-statementnumbersmedian

Median of 3 Numbers: Without using Array or Sorting Concept


How can I calculate the median of three given numbers without using any array. Can we do it by simple calculation or comparison?

What i have tried so far:

#include<stdio.h> 
#include<conio.h> 
void main() 
{ 
  int a[3],i,n=3; 
  float m;
  clrscr();
  printf("Enter the elements:\n"); 
     for(i=0;i<n;i++) 
     { 
        scanf("%d",&a[i]); 
     } 
     if(n%2==0) 
     { 
       m=(a[n-1/2]+(a[n/2]))/2; 
     } 
     else 
     { 
       m=a[n/2]; 
     } 
     printf("\nMedian is %f",m); 
     getch(); 
}

Preferred Code Languages: C, Java


Solution

  • Median is a number that is either halfway into the set or you can think of it as middlemost number in the set. so for finding it we will just do the comparisons like below

    median = Math.max(Math.min(a,b), Math.min(Math.max(a,b),c));
    answer reffered from Fastest way of finding the middle value of a triple?