diff --git a/Day-18/q2: Search in Rotated Sorted Array/namita0210--java.md b/Day-18/q2: Search in Rotated Sorted Array/namita0210--java.md new file mode 100644 index 00000000..5640e0ac --- /dev/null +++ b/Day-18/q2: Search in Rotated Sorted Array/namita0210--java.md @@ -0,0 +1,35 @@ +public class namita0210_java { + + public static int search(int[] nums, int target) { + int left = 0; + int right = nums.length - 1; + + while (left <= right) { + int mid = left + (right - left) / 2; + + if (nums[mid] == target) { + return mid; + } + + 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; // Target not found + } + + +}