Created
August 19, 2016 21:17
-
-
Save dgodfrey206/2ec57e810716f11c977d63afd8b52787 to your computer and use it in GitHub Desktop.
Binary search on k-rotated array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
int at(int* arr, int n, int k, int m) { | |
return arr[((m + (n - (k % n))) % n)]; | |
} | |
int rotated_binary_search(int* arr, int n, int k, int key) { | |
int low = 0, high = n-1, mid, v; | |
while (low <= high) { | |
mid = low + (high - low)/2; | |
v = at(arr, n, k, mid + k); | |
if (v < key) | |
low = mid + 1; | |
else if (v > key) | |
high = mid - 1; | |
else | |
return (mid + k) % n; | |
} | |
return -1; | |
} | |
void runBinarySearch(int* arr, int n, int k, int key) { | |
char c = '\n'; | |
std::cout << "Original:\n"; | |
for (int i = 0; i < 2*n; ++i) { | |
if (i < n) std::cout << "(" << i << ") "; | |
else { | |
std::cout << c << " " << arr[i % n]; | |
c = ' '; | |
} | |
} | |
std::cout << '\n'; | |
c = '\n'; | |
std::cout << "\nAfter " << k << " rotation(s):\n"; | |
for (int i = 0; i < 2*n; ++i) { | |
if (i < n) std::cout << "(" << i << ") "; | |
else { | |
std::cout << c << " " << at(arr, n, k, i % n); | |
c = ' '; | |
} | |
} | |
std::cout << '\n'; | |
std::cout << "\nSearch for " << key << " gives: " << rotated_binary_search(arr, n, k, key) << '\n'; | |
} | |
int main() { | |
int arr[] = {5, 12, 22, 32, 59, 60, 63, 72, 101, 1024}; | |
int n = sizeof(arr)/sizeof(int); | |
int key = 1024; | |
runBinarySearch(arr, n, 2, key); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment