Sun, 15 Dec 2024 16:28:05 +0100
add shortcut to binary search when array size is one
src/array_list.c | file | annotate | diff | comparison | revisions | |
tests/test_list.c | file | annotate | diff | comparison | revisions |
--- 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) {
--- 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)); } }