X-Git-Url: http://mj.ucw.cz/gitweb/?a=blobdiff_plain;f=ucw%2Fbinsearch.h;h=99bf33ada43f4e7da260099993707153d57cc1d8;hb=bc5f818d21b7aceaf2c0e263b00aa4295211d8f9;hp=67419563d49b30cfd65f04bd4d276bd96221f2da;hpb=031256ad2e123eec58521f8e3eb9496c197641d2;p=libucw.git diff --git a/ucw/binsearch.h b/ucw/binsearch.h index 67419563..99bf33ad 100644 --- a/ucw/binsearch.h +++ b/ucw/binsearch.h @@ -7,11 +7,22 @@ * of the GNU Lesser General Public License. */ +/*** + * [[defs]] + * Definitions + * ----------- + ***/ + +/** + * Find the first element not lower than @x in the sorted array @ary of @N elements (non-decreasing order). + * Returns the index of the found element or @N if no exists. Uses `ary_lt_x(ary,i,x)` to compare the @i'th element with @x. + * The time complexity is `O(log(N))`. + **/ #define BIN_SEARCH_FIRST_GE_CMP(ary,N,x,ary_lt_x) ({ \ - uns l = 0, r = (N); \ + uint l = 0, r = (N); \ while (l < r) \ { \ - uns m = (l+r)/2; \ + uint m = (l+r)/2; \ if (ary_lt_x(ary,m,x)) \ l = m+1; \ else \ @@ -20,7 +31,18 @@ l; \ }) +/** + * The default comparision macro for @BIN_SEARCH_FIRST_GE_CMP(). + **/ #define ARY_LT_NUM(ary,i,x) (ary)[i] < (x) +/** + * Same as @BIN_SEARCH_FIRST_GE_CMP(), but uses the default `<` operator for comparisions. + **/ #define BIN_SEARCH_FIRST_GE(ary,N,x) BIN_SEARCH_FIRST_GE_CMP(ary,N,x,ARY_LT_NUM) + +/** + * Search the sorted array @ary of @N elements (non-decreasing) for the first occurence of @x. + * Returns the index or -1 if no such element exists. Uses the `<` operator for comparisions. + **/ #define BIN_SEARCH_EQ(ary,N,x) ({ int i = BIN_SEARCH_FIRST_GE(ary,N,x); if (i >= (N) || (ary)[i] != (x)) i=-1; i; })