-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinsearchrotarr.cpp
More file actions
66 lines (55 loc) · 1.69 KB
/
binsearchrotarr.cpp
File metadata and controls
66 lines (55 loc) · 1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
#include <vector>
using namespace std;
int search(vector<int>& nums, int target) {
int left = 0, right = nums.size() - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
// Check if the middle element is the target
if (nums[mid] == target) {
return mid;
}
// Determine which half is sorted
if (nums[left] <= nums[mid]) {
// Left half is sorted
if (nums[left] <= target && target < nums[mid]) {
right = mid - 1; // Target is in the left half
} else {
left = mid + 1; // Target is in the right half
}
} else {
// Right half is sorted
if (nums[mid] < target && target <= nums[right]) {
left = mid + 1; // Target is in the right half
} else {
right = mid - 1; // Target is in the left half
}
}
}
// If the loop ends, the target is not in the array
return -1;
}
int main() {
vector<int> nums;
int n, target;
// Input array size
cout << "Enter the size of the array: ";
cin >> n;
// Input array elements
cout << "Enter the elements of the array (sorted and possibly rotated): ";
nums.resize(n);
for (int i = 0; i < n; ++i) {
cin >> nums[i];
}
// Input target value
cout << "Enter the target value: ";
cin >> target;
// Perform search and print the result
int result = search(nums, target);
if (result != -1) {
cout << "Target found at index: " << result << endl;
} else {
cout << "Target not found in the array." << endl;
}
return 0;
}