diff --git a/algorithms/CPlusPlus/Arrays/search-sorted-rotated.cpp b/algorithms/CPlusPlus/Arrays/search-sorted-rotated.cpp new file mode 100644 index 00000000..f2a58cb8 --- /dev/null +++ b/algorithms/CPlusPlus/Arrays/search-sorted-rotated.cpp @@ -0,0 +1,48 @@ +//Description : Searching element in a sorted-rotated array using binary search +#include +using namespace std; +int search_array(vector arr, int item) { + int low = 0; + int high = arr.size() - 1; + while (low <= high) { + int mid = low + (high-low)/2; //Calculating middle index + if (arr[mid] == item) { //If the element at middle index is equal to the item then we return the middle index + return mid; + } + else if (arr[mid] > arr[low]) { //Here we check whether left half of the array is sorted or not . + if ((arr[low] <= item) && (item= item) && (item>arr[mid])) { //We check whether our item is smaller or equal to the upper index + low = mid + 1; //If yes, then we start our search within the range (mid+1,high) + } + else { + high = mid - 1; //If item is greater than the element at higher index then we start + } //our search in the range(low,mid-1) + } + } + return -1; +} +int main() { + int t ; + int n; + int item; + vector arr; + cin >> t; //Size of the array + while (t--) { + cin >> n; + arr.push_back(n); + } + cin >> item; + int found = search_array(arr, item); + cout << found << endl; + return 0; + //Time Complexity : O(log t) + //Ex: t=5, arr=[10,20,30,40,50,8,9], item=30 + //found = 2 +} diff --git a/algorithms/CPlusPlus/README.md b/algorithms/CPlusPlus/README.md index 8be84cb0..47c0e3ba 100644 --- a/algorithms/CPlusPlus/README.md +++ b/algorithms/CPlusPlus/README.md @@ -8,6 +8,7 @@ 5. [Shift Negatives](Arrays/shift-negatives.cpp) 6. [Boyer–Moore Voting Algorithm](Arrays/boyer_more.cpp) 7. [Reverse Array](Arrays/reverse-array.cpp) +8. [Sorted-Rotated Search Array](Arrays/search-sorted-rotated.cpp) ## Graphs 1. [Bellman Ford Algorithm](Graphs/bellmam-ford.cpp)