TPCCLIB
Loading...
Searching...
No Matches
median.c File Reference

Functions for calculating median. More...

#include "tpcclibConfig.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include "tpcextensions.h"
#include "tpcstatist.h"

Go to the source code of this file.

Functions

double statMedian (double *a, const int n)
double statKthSmallest (double *a, const int n, const int k)

Detailed Description

Functions for calculating median.

Definition in file median.c.

Function Documentation

◆ statKthSmallest()

double statKthSmallest ( double * a,
const int n,
const int k )

Returns the kth smallest value in an array of given data.

Algorithm is based on the book Wirth N. Algorithms + data structures = programs. Englewood Cliffs, Prentice-Hall, 1976.

See also
statMeanSD, doubleMean, statSortDouble, doubleNaNs
Returns
Returns the kth smallest value in a[0..n-1], or NaN in case of an error.
Parameters
aPointer to data array of size n; data is partially sorted. NaNs are not checked but will lead to a wrong result.
nLength of the data array
kThe K value, 0<=K<n.
Note
The K value is zero based.

Definition at line 55 of file median.c.

64 {
65 //printf("\n%s(a[], %u, %u)\n", __func__, n, k); fflush(stdout);
66 if(a==NULL || n<1 || k<0 || k>=n) return(nan(""));
67 if(n==1) return(a[0]);
68
69 int l=0, m=n-1; // note that algorithm does not work with unsigned integers
70 while(l<m) {
71 int i=l, j=m;
72 double x=a[k];
73 do {
74 while(a[i]<x) i++;
75 while(x<a[j]) j--;
76 if(i<=j) {double s=a[i]; a[i]=a[j]; a[j]=s; i++; j--;}
77 } while(i<=j);
78 if(j<k) l=i;
79 if(k<i) m=j;
80 }
81 return(a[k]);
82}

Referenced by statMedian().

◆ statMedian()

double statMedian ( double * a,
const int n )

Returns the median in an array of given data. Algorithm is based on the book Wirth N. Algorithms + data structures = programs. Englewood Cliffs, Prentice-Hall, 1976.

See also
statMeanSD, doubleMean, statSortDouble, statKthSmallest, doubleNaNs, doubleCopyFinite, doubleRange
Returns
Returns the median in array a[0..n-1], or NaN in case of an error.
Parameters
aPointer to data array of size n; data is partially sorted. NaNs are not checked but will lead to a wrong result.
nLength of data array.

Definition at line 25 of file median.c.

31 {
32 if(a==NULL || n<1) return(nan(""));
33 if(n==1) return(a[0]);
34
35 if(n%2) {
36 int k=(n-1)/2;
37 return(statKthSmallest(a, n, k));
38 } else {
39 int k=n/2;
40 double d1=statKthSmallest(a, n, k-1);
41 double d2=statKthSmallest(a, n, k);
42 return(0.5*(d1+d2));
43 }
44}
double statKthSmallest(double *a, const int n, const int k)
Definition median.c:55