diff --git a/src/algorithms/searching/exponential_search.h b/src/algorithms/searching/exponential_search.h new file mode 100644 index 00000000..35c38294 --- /dev/null +++ b/src/algorithms/searching/exponential_search.h @@ -0,0 +1,31 @@ +#ifndef EXPONENTIAL_SEARCH_H +#define EXPONENTIAL_SEARCH_H + +#ifdef __cplusplus +#include "binary_search.h" +#include +#endif + +template int64_t exponential_search(std::vector arr, T key) { + if (arr[0] == key) { + return true; + } + int64_t i = 1, n = arr.size(); + while (i < n && arr[i] < key) { + i *= 2; + } + int64_t lo = i / 2, hi = std::min(i, n - 1); + while (lo <= hi) { + int64_t mid = (lo + hi) / 2; + if (arr[mid] == key) { + return mid; + } else if (arr[mid] < key) { + lo = mid + 1; + } else { + hi = mid - 1; + } + } + return -1; +} + +#endif \ No newline at end of file diff --git a/src/algorithms/searching/linear_search.h b/src/algorithms/searching/linear_search.h new file mode 100644 index 00000000..5aa9ff0f --- /dev/null +++ b/src/algorithms/searching/linear_search.h @@ -0,0 +1,17 @@ +#ifndef LINEAR_SEARCH_H +#define LINEAR_SEARCH_H + +#ifdef __cplusplus +#include +#endif + +template bool linear_search(std::vector arr, T key) { + for (T &x : arr) { + if (x == key) { + return true; + } + } + return false; +} + +#endif \ No newline at end of file diff --git a/tests/algorithms/searching/exponential_search.cc b/tests/algorithms/searching/exponential_search.cc new file mode 100644 index 00000000..13b9c609 --- /dev/null +++ b/tests/algorithms/searching/exponential_search.cc @@ -0,0 +1,10 @@ +#define CATCH_CONFIG_MAIN +#include "../../../src/algorithms/searching/exponential_search.h" +#include "../../catch2/catch.hpp" + +TEST_CASE("testing exponential search") { + std::vector v = {1, 6, 43, 0, 9, 20, 60}; + REQUIRE(exponential_search(v, 6) == 1); + REQUIRE(exponential_search(v, 60) == 6); + REQUIRE(exponential_search(v, -10) == -1); +} \ No newline at end of file diff --git a/tests/algorithms/searching/linear_search.cc b/tests/algorithms/searching/linear_search.cc new file mode 100644 index 00000000..4f30e60d --- /dev/null +++ b/tests/algorithms/searching/linear_search.cc @@ -0,0 +1,9 @@ +#define CATCH_CONFIG_MAIN +#include "../../../src/algorithms/searching/linear_search.h" +#include "../../catch2/catch.hpp" + +TEST_CASE("testing linear search") { + std::vector v = {1, 5, 3, 1, 2, 3, -41, -20}; + REQUIRE(linear_search(v, 5) == true); + REQUIRE(linear_search(v, -40) == false); +} \ No newline at end of file