#include "stdio.h" #define SIZE 4096 // The complexity is O(log n) // because we always half the amount // like N/2 -> N/4 -> N/8 ... N/(2^k) which equals log n 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)); }