MCPcopy Create free account
hub / github.com/KaisenAmin/c_std / algorithm_binary_search

Function algorithm_binary_search

algorithm/algorithm.c:478–503  ·  view source on GitHub ↗

* @brief Performs a binary search to find the index of a value in a sorted range. * * This function performs a binary search on a sorted range `[base, base + num * size)` to find the index * of the value `val`. The range must be sorted according to the same comparison function `comp`. * * @param base Pointer to the start of the sorted array. * @param num Number of elements in the array. * @

Source from the content-addressed store, hash-verified

476 const char *p = a;
477 size_t f = 0, l = n;
478 while (comp(p, a + (--l) * sz) < 0) { }
479 if (l + 1 == n) {
480 while (f < l && !(comp(p, a + (++f) * sz) < 0)) { }
481 }
482 else {
483 while (!(comp(p, a + (++f) * sz) < 0)) { }
484 }
485 while (f < l) {
486 alg_swap_bytes(a + f * sz, a + l * sz, sz);
487 while (comp(p, a + (--l) * sz) < 0) { }
488 while (!(comp(p, a + (++f) * sz) < 0)) { }
489 }
490 if (l) {
491 alg_swap_bytes(a, a + l * sz, sz);
492 }
493 return l;
494}
495
496/* Partition around the pivot a[0] (elements equal to it go right) with
497 * branchless block partitioning (Edelkamp & Weiss, BlockQuicksort, as tuned
498 * in pdqsort). Returns the pivot's final index; *done is set when the range
499 * was already partitioned. */
500ALG_INLINE size_t pdq_partition_right(char *a, size_t n, size_t sz, AlgorithmCompareFunc comp, char *tmp, int *done) {
501 const char *p = a;
502 size_t f = 0, l = n;
503 while (comp(a + (++f) * sz, p) < 0) { }
504 if (f == 1) {
505 while (f < l && !(comp(a + (--l) * sz, p) < 0)) { }
506 }

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected