TPCCLIB
Toggle main menu visibility
Loading...
Searching...
No Matches
libtpcstatist
median.c
Go to the documentation of this file.
1
4
/*****************************************************************************/
5
#include "tpcclibConfig.h"
6
/*****************************************************************************/
7
#include <stdio.h>
8
#include <stdlib.h>
9
#include <math.h>
10
#include <string.h>
11
/*****************************************************************************/
12
#include "
tpcextensions.h
"
13
/*****************************************************************************/
14
#include "
tpcstatist.h
"
15
/*****************************************************************************/
16
17
/*****************************************************************************/
25
double
statMedian
(
28
double
*a,
30
const
int
n
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
}
45
/*****************************************************************************/
46
47
/*****************************************************************************/
55
double
statKthSmallest
(
58
double
*a,
60
const
int
n,
63
const
int
k
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
}
83
/*****************************************************************************/
84
85
/*****************************************************************************/
statKthSmallest
double statKthSmallest(double *a, const int n, const int k)
Definition
median.c:55
statMedian
double statMedian(double *a, const int n)
Definition
median.c:25
tpcextensions.h
Header file for library libtpcextensions.
tpcstatist.h
Header file for libtpcstatist.
Generated on
for TPCCLIB by
1.18.0