From 688e9104dc882d9d44ba387a8fae864e53b0af62 Mon Sep 17 00:00:00 2001 From: Nikita06211 <120494269+Nikita06211@users.noreply.github.com> Date: Sat, 21 Oct 2023 12:15:41 +0530 Subject: [PATCH 1/2] Create Search_Sorted_RotatedArray.cpp --- .../Cpp/Search_Sorted_RotatedArray.cpp | 61 +++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 DSA_Codesheet/Cpp/Search_Sorted_RotatedArray.cpp diff --git a/DSA_Codesheet/Cpp/Search_Sorted_RotatedArray.cpp b/DSA_Codesheet/Cpp/Search_Sorted_RotatedArray.cpp new file mode 100644 index 0000000..c9ac741 --- /dev/null +++ b/DSA_Codesheet/Cpp/Search_Sorted_RotatedArray.cpp @@ -0,0 +1,61 @@ +#include +#include + +using namespace std; + +int searchInRotatedArray(const vector& nums, int target) { + int low = 0, high = nums.size() - 1; + + while (low <= high) { + int mid = low + (high - low) / 2; + + if (nums[mid] == target) { + return mid; // Found the target + } + + // Check if the left half is sorted + if (nums[low] <= nums[mid]) { + // Check if the target lies in the left half + if (nums[low] <= target && target < nums[mid]) { + high = mid - 1; + } else { + low = mid + 1; + } + } else { // Right half is sorted + // Check if the target lies in the right half + if (nums[mid] < target && target <= nums[high]) { + low = mid + 1; + } else { + high = mid - 1; + } + } + } + + return -1; // Target not found +} + +int main() { + cout << "Enter the size of the rotated sorted array: "; + int n; + cin >> n; + + cout << "Enter the elements of the rotated sorted array: "; + vector rotatedArray(n); + for (int i = 0; i < n; ++i) { + cin >> rotatedArray[i]; + } + + int target; + cout << "Enter the target element to search: "; + cin >> target; + + int result = searchInRotatedArray(rotatedArray, target); + + if (result != -1) { + cout << "Element " << target << " found at index " << result << endl; + } else { + cout << "Element " << target << " not found in the array" << endl; + } + + return 0; +} From 30ebe8e22bcd0e573db633f25a1fce8844bc2365 Mon Sep 17 00:00:00 2001 From: Nikita06211 <120494269+Nikita06211@users.noreply.github.com> Date: Sat, 21 Oct 2023 12:17:38 +0530 Subject: [PATCH 2/2] Rename Search_Sorted_RotatedArray.cpp to Search_Rotated_SortedArray.cpp --- ...rch_Sorted_RotatedArray.cpp => Search_Rotated_SortedArray.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename DSA_Codesheet/Cpp/{Search_Sorted_RotatedArray.cpp => Search_Rotated_SortedArray.cpp} (100%) diff --git a/DSA_Codesheet/Cpp/Search_Sorted_RotatedArray.cpp b/DSA_Codesheet/Cpp/Search_Rotated_SortedArray.cpp similarity index 100% rename from DSA_Codesheet/Cpp/Search_Sorted_RotatedArray.cpp rename to DSA_Codesheet/Cpp/Search_Rotated_SortedArray.cpp