C 語言中的中位數程式



中位數是排序列表中居中的值。要找到中位數,我們需將列表按升序或降序排序。

例如,將 3、5、2、7、3 列表作為輸入列表。要找出中位數,我們首先重新排列為 2、3、3、5、7。我們發現位置為 3 的值 ((5 + 1)/2) 是 3。因此此列表中的中位數為 3。

演算法

此程式的演算法非常簡單 −

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 median
STOP

虛擬碼

我們可以根據演算法匯出虛擬碼,如下 -

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

end procedure

實現

此演算法的實現如下 −

#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;
}

輸出

程式輸出應該是 −

Median = 5 
mathematical_programs_in_c.htm
廣告
© . All rights reserved.