Skip to content

Instantly share code, notes, and snippets.

@misterpoloy
Last active April 16, 2020 05:29
Show Gist options
  • Save misterpoloy/09bb0c58f8eb22b868f8a8f02a379fc0 to your computer and use it in GitHub Desktop.
Save misterpoloy/09bb0c58f8eb22b868f8a8f02a379fc0 to your computer and use it in GitHub Desktop.
Count how many times a circular array has been rotated in cpp
// https://www.youtube.com/watch?v=4qjprDkJrjY&list=PL2_aWCzGMAwL3ldWlrii6YeLszojgH77j&index=6
#include <iostream>
int ArrayCountRotation(int* A, int n) {
/**
// low <= high
// A[mid] menor a next y prev
// binary search
// binary search
*/
int low = 0;
int high = n - 1;
while (low <= high) {
if (A[low] <= A[high]) {
return low;
}
int mid = low + (high - low) / 2;
int prev= (mid + n - 1) % n;
int next = (mid + 1) % n;
if (A[mid] <= A[prev] && A[mid] <= A[next]) {
return mid;
} else if (A[mid] <= A[high]) {
high = mid - 1;
} else if (A[mid] >= A[low]) {
low = mid + 1;
}
}
return -1;
}
int main() {
int arr[] = { 11, 12, 15, 18, 2, 5, 6, 8 };
int n = sizeof(arr) / sizeof(arr[0]);
int counter = ArrayCountRotation(arr, n);
std::cout << counter << " times" << std::endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment