Skip to content

Commit

Permalink
Search in rotated array
Browse files Browse the repository at this point in the history
Signed-off-by: begeekmyfriend <[email protected]>
  • Loading branch information
begeekmyfriend committed Sep 13, 2017
1 parent 5a3738a commit 63c8632
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
2 changes: 2 additions & 0 deletions 081_search_in_rotated_sorted_array_ii/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
all:
gcc -O2 -o test search_rotated_array.c
62 changes: 62 additions & 0 deletions 081_search_in_rotated_sorted_array_ii/search_rotated_array.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
#include <stdio.h>
#include <stdlib.h>

static int binary_search(int *nums, int size, int target)
{
int low = -1;
int high = size;
while (low + 1 < high) {
int mid = low + (high - low) / 2;
if (target > nums[mid]) {
low = mid;
} else {
high = mid;
}
}
if (high == size || nums[high] != target) {
return -1;
} else {
return high;
}
}

static int search(int* nums, int numsSize, int target) {
if (numsSize <= 0) {
return -1;
}
if (numsSize == 1) {
return target == nums[0] ? 0 : -1;
}

int i;
for (i = 1; i < numsSize; i++) {
if (nums[i] < nums[i - 1]) {
break;
}
}

if (i == 0) {
return binary_search(nums, numsSize, target);
} else if (target >= nums[0]) {
return binary_search(nums, i, target);
} else if (target <= nums[numsSize - 1]) {
int index = binary_search(nums + i, numsSize - i, target);
return index >= 0 ? index + i : -1;
} else {
return -1;
}
}

int main(int argc, char **argv)
{
int i;
int target = atoi(argv[1]);
int size = argc - 2;
int *nums = malloc(size * sizeof(int));

for (i = 0; i < argc - 2; i++) {
nums[i] = atoi(argv[i + 2]);
}
printf("%d\n", search(nums, size, target));
return 0;
}

0 comments on commit 63c8632

Please sign in to comment.