Skip to content

Instantly share code, notes, and snippets.

@cs-fedy
Created August 24, 2020 15:16
Show Gist options
  • Save cs-fedy/d16c8c9ae7f8ab6107e047686b4bede2 to your computer and use it in GitHub Desktop.
Save cs-fedy/d16c8c9ae7f8ab6107e047686b4bede2 to your computer and use it in GitHub Desktop.
Search an element in a sorted and rotated array in C.
int get_pivot(int * arr, int arr_size) {
int index = 1;
while(index < arr_size && arr[index] > arr[index - 1]) {
index++;
}
if (index >= arr_size)
return -1;
return index;
}
int binary_search(int x, int * arr, int start, int end) {
if (start > end)
return -1;
int middle = (start + end) / 2;
if (arr[middle] == x)
return middle;
else if (x > arr[middle])
return binary_search(x, arr, middle + 1, end);
return binary_search(x, arr, start, middle - 1);
}
int find_x(int x, int * arr, int arr_size) {
int pivot = get_pivot(arr, arr_size);
if (pivot == -1)
return binary_search(x, arr, 0, arr_size - 1);
if (arr[0] < x)
return binary_search(x, arr, 1, pivot - 1);
return binary_search(x, arr, pivot, arr_size - 1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment