TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
exponential_search.cpp
Go to the documentation of this file.
1
15#include <cassert>
16#include <cmath>
17#include <cstdint>
18#ifdef _MSC_VER
19#include <string> // use for MS Visual C++
20#else
21#include <cstring> // for all other compilers
22#endif
23
33template <class Type>
34inline Type* binary_s(Type* array, size_t size, Type key) {
35 int32_t lower_index(0), upper_index(size - 1), middle_index;
36
37 while (lower_index <= upper_index) {
38 middle_index = std::floor((lower_index + upper_index) / 2);
39
40 if (*(array + middle_index) < key)
41 lower_index = (middle_index + 1);
42 else if (*(array + middle_index) > key)
43 upper_index = (middle_index - 1);
44 else
45 return (array + middle_index);
46 }
47
48 return nullptr;
49}
50
58template <class Type>
59Type* struzik_search(Type* array, size_t size, Type key) {
60 uint32_t block_front(0), block_size = size == 0 ? 0 : 1;
61 while (block_front != block_size) {
62 if (*(array + block_size - 1) < key) {
63 block_front = block_size;
64 (block_size * 2 - 1 < size) ? (block_size *= 2) : block_size = size;
65 continue;
66 }
67 return binary_s<Type>(array + block_front, (block_size - block_front),
68 key);
69 }
70 return nullptr;
71}
72
74int main() {
75 // TEST CASES
76 int* sorted_array = new int[7]{7, 10, 15, 23, 70, 105, 203};
77 assert(struzik_search<int>(sorted_array, 7, 0) == nullptr);
78 assert(struzik_search<int>(sorted_array, 7, 1000) == nullptr);
79 assert(struzik_search<int>(sorted_array, 7, 50) == nullptr);
80 assert(struzik_search<int>(sorted_array, 7, 7) == sorted_array);
81 // TEST CASES
82 delete[] sorted_array;
83 return 0;
84}
Type * binary_s(Type *array, size_t size, Type key)
int main()
Type * struzik_search(Type *array, size_t size, Type key)