5 * <<examples,Examples>>
6 - <<ex_numbers,Numbers>>
7 - <<ex_strings,Strings>>
15 You can find few examples of binary search usage. Although we define only few macros, they can be used
16 for several different cases, for example to find lower elements in a (non-)decreasing array or even to find
17 elements in a (non-)increasing array.
23 static int inc[10] = { 1, 4, 4, 5, 6, 10, 11, 20, 25, 50 };
24 static int dec[3] = { 5, 2, 1 };
26 // find the first equal element
27 printf("%d\n", BIN_SEARCH_EQ(inc, 10, 4)); // prints 1
28 printf("%d\n", BIN_SEARCH_EQ(inc, 10, 15)); // prints -1 (not found)
30 // find the first greater or equal element
31 printf("%d\n", BIN_SEARCH_GE(inc, 10, 9)); // prints 5
32 printf("%d\n", BIN_SEARCH_GE(inc, 10, 10)); // prints 5
33 printf("%d\n", BIN_SEARCH_GE(inc, 10, 4)); // prints 1
34 printf("%d\n", BIN_SEARCH_GE(inc, 10, 99)); // prints 10 (not found)
36 // find the first greater element
37 #define CMP_LE(ary, i, x) ((ary[i]) <= (x))
38 printf("%d\n", BIN_SEARCH_FIRST_GE_CMP(inc, 10, 25, CMP_LE)); // prints 9
40 // find the last lower or equal element (or -1 if not found)
41 printf("%d\n", BIN_SEARCH_FIRST_GE_CMP(inc, 10, 25, CMP_LE) - 1); // prints 8
43 // find the last lower element (or -1 if not found)
44 printf("%d\n", BIN_SEARCH_FIRST_GE(inc, 10, 25) - 1); // prints 7
46 // find the first lower or equal element in the non-increasing array
47 #define CMP_GT(ary, i, x) ((ary[i]) > (x))
48 printf("%d\n", BIN_SEARCH_FIRST_GE_CMP(dec, 3, 4, CMP_GT)); // prints 1
56 static char *str[5] = { "aaa", "abc", "bflmpsvz", "rep", "rep" };
58 #define CMP_STR(ary, i, x) (strcmp((ary[i]), (x)) < 0)
60 printf("%d\n", BIN_SEARCH_GE_CMP(str, 5, "bfl", CMP_STR)); // prints 2