usaa24/a2/binary_search.h
Bohdan Kapliuk 491beb49ed cv7
2024-11-11 19:53:07 +02:00

33 lines
661 B
C

#ifndef BINARY_SEARCH_H
#define BINARY_SEARCH_H
#include <stddef.h>
#include <math.h>
#include <stdio.h>
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