aboutsummaryrefslogtreecommitdiffstats
path: root/include
diff options
context:
space:
mode:
authorjustanothercatgirl <sotov2070@gmail.com>2024-06-20 15:17:05 +0300
committerjustanothercatgirl <sotov2070@gmail.com>2024-06-20 15:17:05 +0300
commit9f76941161380ae52516ede461fec8713ea2e61a (patch)
treea8602ebf7522e7177d65ee986669edf2370459b9 /include
parent86263835b2f9727531d8941733df8e05705354bf (diff)
added binary search function & tests
Diffstat (limited to 'include')
-rw-r--r--include/container.h15
1 files changed, 15 insertions, 0 deletions
diff --git a/include/container.h b/include/container.h
index 775ffc2..7b2b8de 100644
--- a/include/container.h
+++ b/include/container.h
@@ -115,6 +115,7 @@ extern const qsort_cmp_t __qsort_cmps[64];
int array_compare(const void *const a1, const void *const a2, qsort_cmp_t comp);
/// Exact copy of the array. you have to free the pointer as well.
void* array_copy(void* old);
+char array_binary_search(void* array, void* element, qsort_cmp_t cmp);
/* ----------------------------------------------------------------- */
/* ----------------------LINKED LIST HEADER------------------------- */
@@ -340,6 +341,20 @@ int array_compare(const void *const a1, const void *const a2, qsort_cmp_t comp)
/* //TODO!*/
/*}*/
+char array_binary_search(void* array, void* element, qsort_cmp_t cmp) {
+ ssize_t index1 = -1,
+ index2 = array_size(array);
+ if (index2 == 0) return 0;
+ while (1) {
+ ssize_t index3 = (index1+index2)/2;
+ if (index3 == index2 || index3 == index1 || index1 == index2) return 0;
+ int result = cmp(element, (byte*)array + array_element_size(array) * index3);
+ if (result == 0) return 1;
+ if (result < 0) index2 = index3;
+ else if (result > 0) index1 = index3;
+ }
+}
+
#endif // CONTAINER_IMPLEMENTATION