comparison toolboxes/distance_learning/mlr/util/binarysearch.c @ 0:cc4b1211e677 tip

initial commit to HG from Changeset: 646 (e263d8a21543) added further path and more save "camirversion.m"
author Daniel Wolff
date Fri, 19 Aug 2016 13:07:06 +0200
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:cc4b1211e677
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 -DNAN_EQUALS_ZERO binarysearch.c
8 */
9
10 #include "mex.h"
11
12
13 #if NAN_EQUALS_ZERO
14 #define IsNonZero(d) ((d) != 0.0 || mxIsNan(d))
15 #else
16 #define IsNonZero(d) ((d) != 0.0)
17 #endif
18
19 void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
20 {
21 /* Declare variables */
22 int nQuery, nData; /* number of elements */
23 double *pQuery, *pData; /* input arrays */
24 double *positions; /* output array(s) */
25
26 int i;
27
28 if (nrhs != 2) {
29 mexErrMsgTxt("Two input arguments are required.");
30 }
31 if (nlhs > 1) {
32 mexErrMsgTxt("Too many output arguments.");
33 }
34
35 if (!(mxIsDouble(prhs[0])) || !(mxIsDouble(prhs[1]))) {
36 mexErrMsgTxt("Input arrays must be of type double.");
37 }
38
39 nQuery = mxGetNumberOfElements(prhs[0]);
40 nData = mxGetNumberOfElements(prhs[1]);
41 pQuery = (double *)mxGetPr(prhs[0]);
42 pData = (double *)mxGetPr(prhs[1]);
43
44 plhs[0] = mxCreateDoubleMatrix(1, nQuery, mxREAL);
45 positions = mxGetPr(plhs[0]);
46
47 /* Now for the meat */
48
49 for (i = 0; i < nQuery; i++) {
50 positions[i] = 0;
51 positions[i] = binarysearch(pQuery[i], pData, nData);
52 }
53
54 mxSetN(plhs[0], nQuery);
55 }
56
57 int binarysearch(double q, double *data, int n) {
58 int l = 0;
59 int u = n-1;
60 int pivot;
61
62 while (l < u) {
63 pivot = l + (u - l) / 2;
64
65 if (q > data[pivot]) {
66 u = pivot - 1;
67 } else {
68 l = pivot + 1;
69 }
70 }
71
72 /* Break ties to the right */
73 if (l == n || q > data[l]) {
74 return l;
75 } else {
76 return l + 1;
77 }
78
79 }