Files
c3c/lib/std/sort/binarysearch.c3
Pierre Curto 35bffdadc2 improve the sort and collections libs (#853)
* lib/std/sort: unify binarysearch and binarysearch_with; add comments to quicksort

Signed-off-by: Pierre Curto <pierre.curto@gmail.com>

* lib/std/collections: mark List.{len, is_empty, get} with @inline

Signed-off-by: Pierre Curto <pierre.curto@gmail.com>

* lib/std/collections: add PriorityQueueMax; add tests for PriorityQueue and PriorityQueueMax

Signed-off-by: Pierre Curto <pierre.curto@gmail.com>

---------

Signed-off-by: Pierre Curto <pierre.curto@gmail.com>
2023-07-15 19:08:54 +02:00

39 lines
1.2 KiB
C

module std::sort;
/**
* Perform a binary search over the sorted array and return the index
* in [0, array.len) where x would be inserted or cmp(i) is true and cmp(j) is true for j in [i, array.len).
* @require is_searchable(list) "The list must be indexable and support .len or .len()"
* @require !cmp || is_comparer(cmp, list) "Expected a comparison function which compares values"
**/
macro usz binarysearch(list, x, cmp = null) @builtin
{
usz i;
usz len = @len_from_list(list);
for (usz j = len; i < j;)
{
usz half = i + (j - i) / 2;
$if $checks(!cmp):
switch
{
case greater(list[half], x): j = half;
case less(list[half], x): i = half + 1;
default: return half;
}
$else
$switch
$case $checks(cmp(list[0], list[0])):
int res = cmp(list[half], x);
$case $checks(cmp(&list[0], &list[0])):
int res = cmp(&list[half], &x);
$endswitch
switch
{
case res > 0: j = half;
case res < 0: i = half + 1;
default: return half;
}
$endif
}
return i;
}