Skip to content

Commit 7ef4dd6

Browse files
feat(divide-and-conquer): implement search in rotated sorted array using modified binary search
1 parent 7a35585 commit 7ef4dd6

1 file changed

Lines changed: 87 additions & 0 deletions

File tree

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
/**
2+
* Search in Rotated Sorted Array
3+
*
4+
* 📌 Problem:
5+
* Given a sorted array that has been rotated at some pivot,
6+
* find the index of a target element.
7+
*
8+
* Example:
9+
* Array : [4, 5, 6, 7, 0, 1, 2]
10+
* Target : 0
11+
* Output : 4
12+
*
13+
* 💡 Idea:
14+
* Even after rotation, at least one half of the array
15+
* is always sorted.
16+
*
17+
* We use Modified Binary Search:
18+
* 1. Find the middle element
19+
* 2. Identify which half is sorted
20+
* 3. Check if target lies in that half
21+
* 4. Discard the other half
22+
*
23+
* 📊 Time Complexity:
24+
* O(log n)
25+
*
26+
* 📦 Space Complexity:
27+
* O(1)
28+
*/
29+
public class SearchInRotatedSortedArray {
30+
31+
public static void main(String[] args) {
32+
33+
int[] nums = {4, 5, 6, 7, 0, 1, 2};
34+
int target = 0;
35+
36+
int index = search(nums, target);
37+
38+
if (index != -1) {
39+
System.out.println("Target found at index: " + index);
40+
} else {
41+
System.out.println("Target not found");
42+
}
43+
}
44+
45+
/**
46+
* Searches target using Modified Binary Search
47+
*/
48+
public static int search(int[] nums, int target) {
49+
50+
int left = 0;
51+
int right = nums.length - 1;
52+
53+
while (left <= right) {
54+
55+
int mid = left + (right - left) / 2;
56+
57+
// Target found
58+
if (nums[mid] == target) {
59+
return mid;
60+
}
61+
62+
// Left half is sorted
63+
if (nums[left] <= nums[mid]) {
64+
65+
// Target lies within left sorted half
66+
if (target >= nums[left] && target < nums[mid]) {
67+
right = mid - 1;
68+
} else {
69+
left = mid + 1;
70+
}
71+
}
72+
73+
// Right half is sorted
74+
else {
75+
76+
// Target lies within right sorted half
77+
if (target > nums[mid] && target <= nums[right]) {
78+
left = mid + 1;
79+
} else {
80+
right = mid - 1;
81+
}
82+
}
83+
}
84+
85+
return -1;
86+
}
87+
}

0 commit comments

Comments
 (0)