forked from Arunvijay28/Java-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
searchInRotatedSortedArray.java
64 lines (50 loc) · 1.63 KB
/
searchInRotatedSortedArray.java
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
import java.util.Scanner;
public class searchInRotatedSortedArray {
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]) {
if (nums[left] <= target && target < nums[mid]) {
right = mid - 1;
}
else {
left = mid + 1;
}
}
else {
if (nums[mid] < target && target <= nums[right]) {
left = mid + 1;
}
else {
right = mid - 1;
}
}
}
return -1;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of elements in the array: ");
int n = scanner.nextInt();
int[] nums = new int[n];
System.out.println("Enter the elements of the rotated sorted array:");
for (int i = 0; i < n; i++) {
nums[i] = scanner.nextInt();
}
System.out.print("Enter the target value to search for: ");
int target = scanner.nextInt();
int result = search(nums, target);
if (result != -1) {
System.out.println("Target found at index: " + result);
}
else {
System.out.println("Target not found in the array.");
}
scanner.close();
}
}