-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSearchelem_fromrotated.java
108 lines (87 loc) · 2.12 KB
/
Searchelem_fromrotated.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/*
* Class to find the element in a rotated sorted array
*/
public class Searchelem_fromrotated {
/*
* Main method
*/
public static void main(String args[])
{
int arr[] = new int[]{4,5,6,7,0,1,2};
int target = 6;
int pivot = findpivot(arr, target);
int resultindex = search(arr,target,pivot);
System.out.println(resultindex);
}
/*
* Method search() to display the array index
*/
public static int search(int[] nums, int target,int pivot) {
if(nums.length == 0)
{
return 0;
}
if(nums.length == 1 && target == nums[0])
{
return 0;
}
if(nums.length == 1 && target != nums[0])
{
return -1;
}
int indexfound;
if(target >= nums[0])
{
int low = 0;
int high = pivot;
indexfound = binsearch(nums, target, low, high);
}
else
{
int low = pivot + 1;
int high = nums.length - 1;
indexfound = binsearch(nums, target, low, high);
}
return indexfound;
}
/*
* Method findpivot : To find the position where the array is roatated
*/
public static int findpivot(int nums[], int target)
{
for(int i=0;i<nums.length;i++)
{
if(nums[i]<nums[i+1])
{
}
else
{
return i;
}
}
return -1;
}
/*
* Method binsearch : To locate the index using binary search
*/
public static int binsearch(int[] nums, int target, int low, int high)
{
while(high>=low)
{
int mid = (low+high)/2;
if(target == nums[mid])
{
return mid;
}
else if(target > nums[mid])
{
low = mid;
}
else
{
high = mid;
}
}
return -1;
}
}//end of class