From a7a3f11cadbce667bce15b15cf109fc89c81e8e1 Mon Sep 17 00:00:00 2001 From: Rahul Rajeev Pillai <66192267+Ashborn-SM@users.noreply.github.com> Date: Sun, 13 Jun 2021 22:17:23 +0530 Subject: [PATCH] chore(CPlusPlus): add exponential search (#352) --- algorithms/CPlusPlus/README.md | 2 + .../Searching/exponential-search.cpp | 46 +++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 algorithms/CPlusPlus/Searching/exponential-search.cpp diff --git a/algorithms/CPlusPlus/README.md b/algorithms/CPlusPlus/README.md index 532c5abb..17fd91f8 100644 --- a/algorithms/CPlusPlus/README.md +++ b/algorithms/CPlusPlus/README.md @@ -33,6 +33,8 @@ 4. [Finding squareroot using Binary search](Searching/sqrt-monotonic-binary-search.cpp) 5. [KMP String Searching](Searching/kmp.cpp) 6. [Ternary Search](Searching/Ternary-search.cpp) +7. [Interpolation Search](Searching/interpolation-search.cpp) +8. [Exponential Search](Searching/exponential-search.cpp) ## Stacks 1. [Balancing Parenthesis](Stacks/balanced-parenthesis.cpp) diff --git a/algorithms/CPlusPlus/Searching/exponential-search.cpp b/algorithms/CPlusPlus/Searching/exponential-search.cpp new file mode 100644 index 00000000..9e12cada --- /dev/null +++ b/algorithms/CPlusPlus/Searching/exponential-search.cpp @@ -0,0 +1,46 @@ +/* +Exponential search involves two steps, first to find the range within +which the element is found and searching inside that range using +binary search. +*/ + +#include +#include + +int binary_search(std::vector arr, int item, int low, int high){ + int mid; + while(low <= high){ + mid = low + (high - low)/2; + if(arr[mid] == item){ return mid; } + else if(arr[mid] < item){ low = mid + 1; } + else{ high = mid - 1;} + } + return -1; +} + +int exponential_search(std::vector arr, int item){ + int k = 1; + int size = arr.size() - 1; + while(k < size && arr[k] <= item){ k *= 2; } + return binary_search(arr, item, k/2, std::min(k, size)); +} + +int main(){ + std::vector arr; + for(int i=1; i<30; i+=2){ arr.push_back(i); } + for(int i=0; i