From 6036556d78597fcc33d51506333a9cd1edad6c90 Mon Sep 17 00:00:00 2001 From: Namita <46557775+namita0210@users.noreply.github.com> Date: Tue, 23 Jan 2024 16:25:21 +0000 Subject: [PATCH] Day-18 Q2 : reformat and rectify mistakes --- .../namita0210--java.md | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Day-18/q2: Search in Rotated Sorted Array/namita0210--java.md 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 + } + + +}