Update exponential_search.cpp

This commit is contained in:
Divide-et-impera-11 2019-11-30 21:01:52 +01:00 committed by GitHub
parent 51c26b85fe
commit 36a3999f3e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -3,10 +3,9 @@
#include <string> #include <string>
#include <assert.h> #include <assert.h>
using namespaces std; using namespaces std;
template<class Type> inline Type* binary_search(Type *array, size_t size, Type key){ template<class Type> inline Type* binary_s(Type *array, size_t size, Type key) {
int32_t lower_index(0), upper_index(size - 1), middle_index; int32_t lower_index(0), upper_index(size - 1), middle_index;
while (lower_index <= upper_index) while (lower_index <= upper_index) {
{
middle_index = floor((lower_index + upper_index) / 2); middle_index = floor((lower_index + upper_index) / 2);
if (*(array + middle_index) < key) lower_index = (middle_index + 1); if (*(array + middle_index) < key) lower_index = (middle_index + 1);
else if (*(array + middle_index) > key)upper_index = (middle_index - 1); else if (*(array + middle_index) > key)upper_index = (middle_index - 1);
@ -16,14 +15,13 @@ template<class Type> inline Type* binary_search(Type *array, size_t size, Type k
} }
template<class Type> Type* Struzik_Search(Type* array, size_t size, Type key) { template<class Type> Type* Struzik_Search(Type* array, size_t size, Type key) {
uint32_t block_front(0), block_size = size == 0 ? 0 : 1; uint32_t block_front(0), block_size = size == 0 ? 0 : 1;
while (block_front != block_size) while (block_front != block_size) {
{
if (*(array + block_size - 1) < key) { if (*(array + block_size - 1) < key) {
block_front = block_size; block_front = block_size;
(block_size * 2 - 1 < size) ? (block_size *= 2) : block_size = size; (block_size * 2 - 1 < size) ? (block_size *= 2) : block_size = size;
continue; continue;
} }
return binary_search<Type>(array + block_front, (block_size - block_front), key); return binary_s<Type>(array + block_front, (block_size - block_front), key);
} }
return nullptr; return nullptr;
} }