# HG changeset patch # User Mike Becker # Date 1734276485 -3600 # Node ID 2911c1f4a57023a0d77c2fcfb14a7a2bda73c4e7 # Parent 1f22de6977a186b489a65a3401073956d877b436 add shortcut to binary search when array size is one diff -r 1f22de6977a1 -r 2911c1f4a570 src/array_list.c --- a/src/array_list.c Sun Dec 15 16:10:19 2024 +0100 +++ b/src/array_list.c Sun Dec 15 16:28:05 2024 +0100 @@ -435,6 +435,9 @@ return 0; } + // special case: there is only one element and that is smaller + if (size == 1) return 0; + // check the last array element result = cmp_func(elem, array + elem_size * (size - 1)); if (result >= 0) { diff -r 1f22de6977a1 -r 2911c1f4a570 tests/test_list.c --- a/tests/test_list.c Sun Dec 15 16:10:19 2024 +0100 +++ b/tests/test_list.c Sun Dec 15 16:28:05 2024 +0100 @@ -250,6 +250,30 @@ CX_TEST_ASSERT(18 == cx_array_binary_search_inf(array, 18, sizeof(int), &s, cx_cmp_int)); CX_TEST_ASSERT(0 == cx_array_binary_search_sup(array, 18, sizeof(int), &s, cx_cmp_int)); CX_TEST_ASSERT(18 == cx_array_binary_search(array, 18, sizeof(int), &s, cx_cmp_int)); + + // special case - size 0 + s = 40; + CX_TEST_ASSERT(0 == cx_array_binary_search_inf(array, 0, sizeof(int), &s, cx_cmp_int)); + CX_TEST_ASSERT(0 == cx_array_binary_search_sup(array, 0, sizeof(int), &s, cx_cmp_int)); + CX_TEST_ASSERT(0 == cx_array_binary_search(array, 0, sizeof(int), &s, cx_cmp_int)); + + // special case - size 1, searched element is smaller + s = 30; + CX_TEST_ASSERT(1 == cx_array_binary_search_inf(array, 1, sizeof(int), &s, cx_cmp_int)); + CX_TEST_ASSERT(0 == cx_array_binary_search_sup(array, 1, sizeof(int), &s, cx_cmp_int)); + CX_TEST_ASSERT(1 == cx_array_binary_search(array, 1, sizeof(int), &s, cx_cmp_int)); + + // special case - size 1, searched element is larger + s = 50; + CX_TEST_ASSERT(0 == cx_array_binary_search_inf(array, 1, sizeof(int), &s, cx_cmp_int)); + CX_TEST_ASSERT(1 == cx_array_binary_search_sup(array, 1, sizeof(int), &s, cx_cmp_int)); + CX_TEST_ASSERT(1 == cx_array_binary_search(array, 1, sizeof(int), &s, cx_cmp_int)); + + // special case - size 1, element matches + s = 40; + CX_TEST_ASSERT(0 == cx_array_binary_search_inf(array, 1, sizeof(int), &s, cx_cmp_int)); + CX_TEST_ASSERT(0 == cx_array_binary_search_sup(array, 1, sizeof(int), &s, cx_cmp_int)); + CX_TEST_ASSERT(0 == cx_array_binary_search(array, 1, sizeof(int), &s, cx_cmp_int)); } }