forked from MakeContributions/DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
chore(CPlusPlus): add exponential search (MakeContributions#352)
- Loading branch information
1 parent
c3b7736
commit a7a3f11
Showing
2 changed files
with
48 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |