cv7
This commit is contained in:
parent
04b8459061
commit
491beb49ed
33
a2/binary_search.h
Normal file
33
a2/binary_search.h
Normal file
@ -0,0 +1,33 @@
|
|||||||
|
#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
|
||||||
Loading…
Reference in New Issue
Block a user