forked from ravya1108/hactoberfest2023
-
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.
search element in rotated array @hactoberfest2023 ravya1108#175
- Loading branch information
Showing
1 changed file
with
49 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
#include <iostream> | ||
#include <vector> | ||
|
||
int searchInRotatedArray(const std::vector<int>& nums, int target) { | ||
int left = 0; | ||
int right = nums.size() - 1; | ||
|
||
while (left <= right) { | ||
int mid = left + (right - left) / 2; | ||
|
||
if (nums[mid] == target) { | ||
return mid; | ||
} | ||
|
||
// Check which side of the pivot the mid element is on | ||
if (nums[left] <= nums[mid]) { | ||
// Left half is sorted | ||
if (nums[left] <= target && target < nums[mid]) { | ||
right = mid - 1; | ||
} else { | ||
left = mid + 1; | ||
} | ||
} else { | ||
// Right half is sorted | ||
if (nums[mid] < target && target <= nums[right]) { | ||
left = mid + 1; | ||
} else { | ||
right = mid - 1; | ||
} | ||
} | ||
} | ||
|
||
return -1; // Element not found | ||
} | ||
|
||
int main() { | ||
std::vector<int> rotatedArray = {4, 5, 6, 7, 0, 1, 2}; | ||
int target = 0; | ||
|
||
int result = searchInRotatedArray(rotatedArray, target); | ||
|
||
if (result != -1) { | ||
std::cout << "Element " << target << " found at index " << result << std::endl; | ||
} else { | ||
std::cout << "Element " << target << " not found in the array." << std::endl; | ||
} | ||
|
||
return 0; | ||
} |