Skip to content

Commit

Permalink
chore(CPlusPlus): add exponential search (MakeContributions#352)
Browse files Browse the repository at this point in the history
  • Loading branch information
Ashborn-SM authored Jun 13, 2021
1 parent c3b7736 commit a7a3f11
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
2 changes: 2 additions & 0 deletions algorithms/CPlusPlus/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
46 changes: 46 additions & 0 deletions algorithms/CPlusPlus/Searching/exponential-search.cpp
Original file line number Diff line number Diff line change
@@ -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 <iostream>
#include <vector>

int binary_search(std::vector<int> 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<int> 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<int> arr;
for(int i=1; i<30; i+=2){ arr.push_back(i); }
for(int i=0; i<arr.size(); i++){ std::cout << arr[i] << " "; }
std::cout << std::endl;

int index = exponential_search(arr, 15);
std::cout << "Index of 15: " << index << std::endl;

/*
Output:
1 3 5 7 9 11 13 15 17 19 21 23 25 27 29
Index of 15: 7
Time Complexity: O(log(n))
*/

return 0;
}

0 comments on commit a7a3f11

Please sign in to comment.