-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathARRAYSASSIGNMENT.java
More file actions
34 lines (31 loc) · 1.01 KB
/
ARRAYSASSIGNMENT.java
File metadata and controls
34 lines (31 loc) · 1.01 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
import java.util.*;
public class ARRAYSASSIGNMENT {
public static int search(int[] nums, int target) {
int left = 0, right = nums.length - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (nums[mid] == target) {
return mid;
}
if (nums[left] <= nums[mid]) { // Left half is sorted
if (target >= nums[left] && target < nums[mid]) {
right = mid - 1;
} else {
left = mid + 1;
}
} else { // Right half is sorted
if (target > nums[mid] && target <= nums[right]) {
left = mid + 1;
} else {
right = mid - 1;
}
}
}
return -1;
}
public static void main(String args[]) {
int nums[] = { 2, 4, 6, 8, 9 };
int target = 8;
System.out.println(search(nums, target));
}
}