-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsearchinmountain.java
More file actions
80 lines (70 loc) · 2 KB
/
searchinmountain.java
File metadata and controls
80 lines (70 loc) · 2 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
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
public class searchinmountain {
public static void main(String[] args) {
int arr[] = {1,2,3,4,5,3,2,1};
System.out.println(findInMountainArray(3,arr));
}
public static int findInMountainArray(int target, int[] mountainArr)
{
int peak= findPeakElement(mountainArr);
int first= bsearch(mountainArr,target, 0,peak);
if(first!=-1)
{
return first;
}
else
{
return bsearch(mountainArr,target, peak+1,mountainArr.length-1);
}
}
public static int findPeakElement(int[] nums)
{
int beg = 0;
int end = nums.length - 1;
while (beg < end)
{
int mid = beg + (end - beg) / 2;
if (nums[mid] > nums[mid+1])
{
end = mid;
}
else
{
beg = mid + 1;
}
}
return beg;
}
static int bsearch(int[] arr,int ele,int beg,int last)
{
boolean isasc= arr[beg]< arr[last];
while(beg<=last)
{
int mid= (beg+last)/2;
if(arr[mid]==ele)
{
return mid;
}
if(isasc)
{
if(arr[mid]>ele)
{
last= mid-1;
}
else{
beg= mid+1;
}
}
else
{
if(arr[mid]<ele)
{
last= mid-1;
}
else{
beg= mid+1;
}
}
}
return -1;
}
}