目录

Median Program

中值是排序列表中心的值。 要达到中位数,我们需要按升序或降序对列表进行排序。

For Example将3,5,2,7,3列表作为输入列表。 为了找出中位数,首先我们将其重新排序为2,3,3,5,7。我们发现在位置3 ((5+1)/2)是3.所以此列表中的中位数值是3。

算法 (Algorithm)

这个程序的算法很简单 -

START
   Step 1 → Take an integer list A of n values
   Step 2 → Arrange the values in the list in some order, say ascending
   Step 3 → Calculate the middle of list → (n + 1)/2
   Step 4 → Display the middle value as <b class="notranslate">median</b>
STOP

伪代码 (Pseudocode)

我们可以基于该算法导出伪代码,如 -

procedure median()
   Array A
   Size  N
   SORT(A)
   middle = (N + 1)/2
   DISPLAY A[middle] as median
end procedure

实现 (Implementation)

该算法的实现如下 -

#include <stdio.h>
void swap(int *p,int *q) {
   int t;
   t=*p; 
   *p=*q; 
   *q=t;
}
void sort(int a[],int n) { 
   int i,j,temp;
   for(i = 0;i < n-1;i++) {
      for(j = 0;j < n-i-1;j++) {
         if(a[j] > a[j+1])
            swap(&a[j],&a[j+1]);
      }
   }
}
int main() {
   int a[] = {6,3,8,5,1};
   int n = 5;
   int sum,i;
   sort(a,n);
   n = (n+1)/2 - 1;      // -1 as array indexing in C starts from 0
   printf("Median = %d ", a[n]);
   return 0;
}

输出 (Output)

该方案的产出应该是 -

Median = 5 
↑回到顶部↑
WIKI教程 @2018