summary refs log tree commit diff stats
path: root/c/binary-search/binary_search.c
diff options
context:
space:
mode:
Diffstat (limited to 'c/binary-search/binary_search.c')
-rw-r--r--c/binary-search/binary_search.c16
1 files changed, 16 insertions, 0 deletions
diff --git a/c/binary-search/binary_search.c b/c/binary-search/binary_search.c
new file mode 100644
index 0000000..fe122d4
--- /dev/null
+++ b/c/binary-search/binary_search.c
@@ -0,0 +1,16 @@
+#include "binary_search.h"
+
+const int *binary_search(int value, const int *arr, size_t length) {
+    size_t left = 0, right = length;
+    while (left < right) {
+        size_t mid = left + (right - left) / 2;
+
+        if (arr[mid] < value)
+            left = mid + 1;
+        else if (arr[mid] > value)
+            right = mid;
+        else
+            return &arr[mid];
+    }
+    return NULL;
+}