From 491beb49ed0e1dc704c0f47e7d8881d3be8cd215 Mon Sep 17 00:00:00 2001 From: Bohdan Kapliuk Date: Mon, 11 Nov 2024 19:53:07 +0200 Subject: [PATCH] cv7 --- a2/binary_search.h | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) create mode 100644 a2/binary_search.h diff --git a/a2/binary_search.h b/a2/binary_search.h new file mode 100644 index 0000000..7589424 --- /dev/null +++ b/a2/binary_search.h @@ -0,0 +1,33 @@ +#ifndef BINARY_SEARCH_H +#define BINARY_SEARCH_H + +#include +#include +#include + +const int *binary_search(int value, const int *arr, size_t length) { + if (length == 0) { + return NULL; + } + + size_t left = 0; + size_t right = length - 1; + + while (left <= right) { + size_t middle = left + (right - left) / 2; + + if (arr[middle] == value) { + return &arr[middle]; + } else if (arr[middle] > value) { + if (middle == 0) { + break; + } + right = middle - 1; + } else { + left = middle + 1; + } + } + return NULL; +} + +#endif \ No newline at end of file