Skip to content

Commit 1d0a362

Browse files
authored
Merge pull request neetcode-gh#931 from PritomKarmokar/c-solution-Search-in-Rotated-Sorted-Array
adding 33-Search-in-Rotated-Sorted-Array.c
2 parents ec6de2b + 6711941 commit 1d0a362

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

c/33-Search-in-Rotated-Sorted-Array.c

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
int findPivotIndex(int* nums, int numsSize)
2+
{
3+
int s = 0;
4+
int e = numsSize;
5+
6+
while(s <= e){
7+
8+
int m = s + (e - s)/2;
9+
10+
if(m < e && nums[m] > nums[m+1]){
11+
return m;
12+
}
13+
else if(s < m && nums[m] < nums[m-1]){
14+
return m - 1;
15+
}
16+
else if(nums[s] < nums[m]){
17+
s = m + 1;
18+
}
19+
else if(nums[s] >= nums[m]){
20+
e = m - 1;
21+
}
22+
}
23+
24+
// If the array is not rotated then last position will be the pivot element.
25+
26+
return numsSize;
27+
}
28+
29+
int binarySearch(int *nums, int s, int e, int target)
30+
{
31+
while(s <= e){
32+
33+
int m = s + (e - s)/2;
34+
35+
if(nums[m] == target){
36+
return m;
37+
}
38+
else if(nums[m] < target){
39+
s = m + 1;
40+
}
41+
else{
42+
e = m - 1;
43+
}
44+
}
45+
46+
return -1;
47+
}
48+
49+
int search(int* nums, int numsSize, int target){
50+
51+
int n = numsSize - 1;
52+
53+
int pivotIndex = findPivotIndex(nums, n);
54+
55+
int firstTry = binarySearch(nums, 0, pivotIndex, target);
56+
57+
if(firstTry != -1){
58+
return firstTry;
59+
}
60+
61+
return binarySearch(nums, pivotIndex + 1, n, target);
62+
}

0 commit comments

Comments
 (0)