Mercurial > hg > camir-aes2014
comparison toolboxes/distance_learning/mlr/util/binarysearch.c @ 0:e9a9cd732c1e tip
first hg version after svn
author | wolffd |
---|---|
date | Tue, 10 Feb 2015 15:05:51 +0000 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
-1:000000000000 | 0:e9a9cd732c1e |
---|---|
1 /* CREATED:2010-01-17 08:12:57 by Brian McFee <bmcfee@cs.ucsd.edu> */ | |
2 /* binarysearch.c | |
3 * | |
4 * binary search | |
5 * | |
6 * Compile: | |
7 * mex binarysearch.c | |
8 */ | |
9 | |
10 #include "mex.h" | |
11 | |
12 | |
13 void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) | |
14 { | |
15 /* Declare variables */ | |
16 int nQuery, nData; /* number of elements */ | |
17 double *pQuery, *pData; /* input arrays */ | |
18 double *positions; /* output array(s) */ | |
19 | |
20 int i; | |
21 | |
22 if (nrhs != 2) { | |
23 mexErrMsgTxt("Two input arguments are required."); | |
24 } | |
25 if (nlhs > 1) { | |
26 mexErrMsgTxt("Too many output arguments."); | |
27 } | |
28 | |
29 if (!(mxIsDouble(prhs[0])) || !(mxIsDouble(prhs[1]))) { | |
30 mexErrMsgTxt("Input arrays must be of type double."); | |
31 } | |
32 | |
33 nQuery = mxGetNumberOfElements(prhs[0]); | |
34 nData = mxGetNumberOfElements(prhs[1]); | |
35 pQuery = (double *)mxGetPr(prhs[0]); | |
36 pData = (double *)mxGetPr(prhs[1]); | |
37 | |
38 plhs[0] = mxCreateDoubleMatrix(1, nQuery, mxREAL); | |
39 positions = mxGetPr(plhs[0]); | |
40 | |
41 /* Now for the meat */ | |
42 | |
43 for (i = 0; i < nQuery; i++) { | |
44 positions[i] = 0; | |
45 positions[i] = binarysearch(pQuery[i], pData, nData); | |
46 } | |
47 | |
48 mxSetN(plhs[0], nQuery); | |
49 } | |
50 | |
51 int binarysearch(double q, double *data, int n) { | |
52 int l = 0; | |
53 int u = n-1; | |
54 int pivot; | |
55 | |
56 while (l < u) { | |
57 pivot = l + (u - l) / 2; | |
58 | |
59 if (q > data[pivot]) { | |
60 u = pivot - 1; | |
61 } else { | |
62 l = pivot + 1; | |
63 } | |
64 } | |
65 | |
66 /* Break ties to the right */ | |
67 if (l == n || q > data[l]) { | |
68 return l; | |
69 } else { | |
70 return l + 1; | |
71 } | |
72 | |
73 } |