33 lines
661 B
C
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 |