fixes incorrect result from cx_array_binary_search() when searched element is smaller than the entire array

Tue, 17 Sep 2024 23:19:03 +0200

author
Mike Becker <universe@uap-core.de>
date
Tue, 17 Sep 2024 23:19:03 +0200
changeset 885
878a450e79bd
parent 884
d375d8056262
child 886
5f5514bb104b

fixes incorrect result from cx_array_binary_search() when searched element is smaller than the entire array

relates to #424

src/array_list.c file | annotate | diff | comparison | revisions
src/cx/array_list.h file | annotate | diff | comparison | revisions
tests/test_list.c file | annotate | diff | comparison | revisions
--- a/src/array_list.c	Tue Sep 17 23:11:17 2024 +0200
+++ b/src/array_list.c	Tue Sep 17 23:19:03 2024 +0200
@@ -251,7 +251,9 @@
 
     // check the first array element
     result = cmp_func(elem, array);
-    if (result <= 0) {
+    if (result < 0) {
+        return size;
+    } else if (result == 0) {
         return 0;
     }
 
--- a/src/cx/array_list.h	Tue Sep 17 23:11:17 2024 +0200
+++ b/src/cx/array_list.h	Tue Sep 17 23:19:03 2024 +0200
@@ -300,6 +300,7 @@
  *
  * In other words, this function returns the index of the largest element
  * in \p arr that is less or equal to \p elem with respect to \p cmp_func.
+ * When no such element exists, \p size is returned.
  *
  * If \p elem is contained in the array, this is identical to
  * #cx_array_binary_search().
@@ -312,7 +313,7 @@
  * @param elem_size the size of one element
  * @param elem the element to find
  * @param cmp_func the compare function
- * @return the index of the closest element in the array
+ * @return the index of the largest upper bound, or \p size
  */
 size_t cx_array_binary_search_inf(
         void const *arr,
--- a/tests/test_list.c	Tue Sep 17 23:11:17 2024 +0200
+++ b/tests/test_list.c	Tue Sep 17 23:19:03 2024 +0200
@@ -173,6 +173,12 @@
         s = 69;
         CX_TEST_ASSERT(11 == cx_array_binary_search_inf(array, 18, sizeof(int), &s, cx_cmp_int));
         CX_TEST_ASSERT(18 == cx_array_binary_search(array, 18, sizeof(int), &s, cx_cmp_int));
+        s = 95;
+        CX_TEST_ASSERT(17 == cx_array_binary_search_inf(array, 18, sizeof(int), &s, cx_cmp_int));
+        CX_TEST_ASSERT(18 == cx_array_binary_search(array, 18, sizeof(int), &s, cx_cmp_int));
+        s = 30;
+        CX_TEST_ASSERT(18 == cx_array_binary_search_inf(array, 18, sizeof(int), &s, cx_cmp_int));
+        CX_TEST_ASSERT(18 == cx_array_binary_search(array, 18, sizeof(int), &s, cx_cmp_int));
     }
 }
 

mercurial