Skip to content

Commit

Permalink
Create searchInrotated.cpp
Browse files Browse the repository at this point in the history
search element in rotated array @hactoberfest2023 ravya1108#175
  • Loading branch information
tushar453 authored Oct 10, 2023
1 parent 1c13757 commit 3d77bfa
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions searchInrotated.cpp
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;
}

0 comments on commit 3d77bfa

Please sign in to comment.