Skip to content

Commit 0da0cc3

Browse files
ADD Search-in-Rotated-Sorted-Array problem #51
1 parent 27560c1 commit 0da0cc3

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
using System;
2+
3+
public class Solution
4+
{
5+
public static void Main(string[] args)
6+
{
7+
int[] nums = { 3, 1 };
8+
Console.WriteLine(Search(nums, 1));
9+
10+
Console.ReadKey();
11+
}
12+
13+
public static int Search(int[] nums, int target)
14+
{
15+
if (nums == null || nums.Length == 0)
16+
return -1;
17+
18+
int left = 0, right = nums.Length - 1;
19+
20+
while (left <= right)
21+
{
22+
int medium = left + ((right - left) / 2);
23+
24+
if (nums[medium] == target)
25+
return medium;
26+
27+
// Left Sorted Portion
28+
else if (nums[medium] >= nums[left])
29+
{
30+
if (target < nums[medium] && target >= nums[left])
31+
right = medium - 1;
32+
else
33+
left = medium + 1;
34+
}
35+
36+
// Right Sorted Portion
37+
else
38+
{
39+
if (target > nums[medium] && target <= nums[right])
40+
left = medium + 1;
41+
else
42+
right = medium - 1;
43+
}
44+
45+
}
46+
47+
return -1;
48+
}
49+
}
50+

0 commit comments

Comments
 (0)