From 2a1c977954e2a16f30310c3bc6eb9e2108367882 Mon Sep 17 00:00:00 2001 From: NaiJi Date: Mon, 22 Apr 2024 00:14:07 +0400 Subject: [PATCH] 4 --- .../4. Binary Search.c | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 The Last Algorithms Course You'll Need/4. Binary Search.c diff --git a/The Last Algorithms Course You'll Need/4. Binary Search.c b/The Last Algorithms Course You'll Need/4. Binary Search.c new file mode 100644 index 0000000..b15f400 --- /dev/null +++ b/The Last Algorithms Course You'll Need/4. Binary Search.c @@ -0,0 +1,44 @@ +#include "stdio.h" + +#define SIZE 4096 + +int binary_search(int array[], int size, int offset, int value) +{ + int pivot = size / 2; + int current_value = array[offset + pivot]; + printf("At %d\n", offset + pivot); + + if (current_value == value) + { + return 1; + } + + + if (pivot > 0) + { + if (current_value > value) + return binary_search(array, pivot, offset, value); + else + return binary_search(array, pivot, offset + pivot, value); + } + + return 0; +} + +int main() +{ + int array[SIZE]; + for (int i = 0; i < SIZE; ++i) + array[i] = i; + + printf("1 if found: %d\n", binary_search(array, SIZE, 0, 5243)); + printf("1 if found: %d\n", binary_search(array, SIZE, 0, 1)); + printf("1 if found: %d\n", binary_search(array, SIZE, 0, 1044)); +// for (int i = 0; i < SIZE; ++i) +// if (!binary_search(array, SIZE, 0, i)) +// printf("YOU FUCKED UP!!! at index %d\n", i); + printf("1 if found: %d\n", binary_search(array, SIZE, 0, SIZE)); + array[14] = 13; + printf("1 if found: %d\n", binary_search(array, SIZE, 0, 14)); + +}