--- a/tests/test_list.c Sat Nov 22 19:16:27 2025 +0100 +++ b/tests/test_list.c Sun Nov 23 12:19:24 2025 +0100 @@ -484,6 +484,61 @@ } } +CX_TEST(test_array_binary_search_with_duplicates) { + int array[18] = { + 40, 50, 55, 55, 55, 57, 57, 58, 60, + 62, 64, 65, 70, 70, 70, 78, 80, 90 + }; + int s; + CX_TEST_DO { + // exact matches (largest index on duplicate) + s = 40; + CX_TEST_ASSERT(0 == cx_array_binary_search(array, 18, sizeof(int), &s, cx_cmp_int)); + s = 50; + CX_TEST_ASSERT(1 == cx_array_binary_search(array, 18, sizeof(int), &s, cx_cmp_int)); + s = 55; + CX_TEST_ASSERT(4 == cx_array_binary_search(array, 18, sizeof(int), &s, cx_cmp_int)); + s = 57; + CX_TEST_ASSERT(6 == cx_array_binary_search(array, 18, sizeof(int), &s, cx_cmp_int)); + s = 58; + CX_TEST_ASSERT(7 == cx_array_binary_search(array, 18, sizeof(int), &s, cx_cmp_int)); + s = 65; + CX_TEST_ASSERT(11 == cx_array_binary_search(array, 18, sizeof(int), &s, cx_cmp_int)); + s = 70; + CX_TEST_ASSERT(14 == cx_array_binary_search(array, 18, sizeof(int), &s, cx_cmp_int)); + s = 78; + CX_TEST_ASSERT(15 == cx_array_binary_search(array, 18, sizeof(int), &s, cx_cmp_int)); + + // not found + s = 30; + CX_TEST_ASSERT(18 == cx_array_binary_search(array, 18, sizeof(int), &s, cx_cmp_int)); + s = 75; + CX_TEST_ASSERT(18 == cx_array_binary_search(array, 18, sizeof(int), &s, cx_cmp_int)); + s = 52; + CX_TEST_ASSERT(18 == cx_array_binary_search(array, 18, sizeof(int), &s, cx_cmp_int)); + s = 100; + CX_TEST_ASSERT(18 == cx_array_binary_search(array, 18, sizeof(int), &s, cx_cmp_int)); + + // infimum + s = 55; // also yields an exact match + CX_TEST_ASSERT(4 == cx_array_binary_search_inf(array, 18, sizeof(int), &s, cx_cmp_int)); + s = 56; + CX_TEST_ASSERT(4 == cx_array_binary_search_inf(array, 18, sizeof(int), &s, cx_cmp_int)); + s = 75; + CX_TEST_ASSERT(14 == cx_array_binary_search_inf(array, 18, sizeof(int), &s, cx_cmp_int)); + + // supremum (smallest index) + s = 52; + CX_TEST_ASSERT(2 == cx_array_binary_search_sup(array, 18, sizeof(int), &s, cx_cmp_int)); + s = 66; + CX_TEST_ASSERT(12 == cx_array_binary_search_sup(array, 18, sizeof(int), &s, cx_cmp_int)); + s = 75; + CX_TEST_ASSERT(15 == cx_array_binary_search_sup(array, 18, sizeof(int), &s, cx_cmp_int)); + s = 70; // exact match, we want the smallest index + CX_TEST_ASSERT(12 == cx_array_binary_search_sup(array, 18, sizeof(int), &s, cx_cmp_int)); + } +} + typedef struct node { struct node *next; struct node *prev; @@ -3344,6 +3399,7 @@ cx_test_register(suite, test_array_insert_sorted); cx_test_register(suite, test_array_insert_unique); cx_test_register(suite, test_array_binary_search); + cx_test_register(suite, test_array_binary_search_with_duplicates); cx_test_register(suite, test_list_arl_create); cx_test_register(suite, test_list_arl_create_simple);