Skip to content

Commit abf57bb

Browse files
Accepted
1 parent ad6e539 commit abf57bb

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
* Created by gouthamvidyapradhan on 10/04/2017.
3+
* Accepted
4+
*/
5+
public class SearchRotatedSortedArray
6+
{
7+
/**
8+
* Main method
9+
* @param args
10+
* @throws Exception
11+
*/
12+
public static void main(String[] args) throws Exception
13+
{
14+
int[] A = {5, 4, 3, 2, 1};
15+
System.out.println(new SearchRotatedSortedArray().search(A, 4));
16+
}
17+
18+
public int search(int[] nums, int target)
19+
{
20+
if(nums.length == 0) return -1;
21+
if(nums.length == 1)
22+
{
23+
return (nums[0] == target) ? 0 : -1;
24+
}
25+
int low = 0, high = nums.length - 1;
26+
while(low < high)
27+
{
28+
int mid = (low + high) / 2;
29+
if(nums[mid] == target)
30+
return mid;
31+
if((nums[mid] <= nums[low]) && (target > nums[mid] && target <= nums[high]) ||
32+
(nums[low] <= nums[mid] && (target < nums[low] || target > nums[mid])))
33+
low = mid + 1;
34+
else high = mid - 1;
35+
}
36+
return (nums[low] == target) ? low : -1;
37+
}
38+
39+
}

0 commit comments

Comments
 (0)