Binary Search on Rotated Array

Search for a given number in a sorted array, with unique elements, that has been rotated by some arbitrary number. Return -1 if the number does not exist.
 avatar
unknown
c_cpp
4 years ago
990 B
6
Indexable
#include <functional>

// gets index of smallest value
int get_offset(vector<int>& arr) {
    for (int i = 1; i < arr.size(); i++) {
        if (arr[i] < arr[i - 1])
            return i;
    }
    return 0;
}

int binary_search(vector<int>& arr, int key, int left, int right, function<int(int)> t) {
    int mid = (right - left) / 2;
    if (mid == 0 && arr[t(mid)] != key)
        return -1;
    mid = mid + left;
    if (arr[t(mid)] == key) {
        return mid;
    } else if (arr[t(mid)] < key) {
        return binary_search(arr, key, mid, right, t);
    } else {
        return binary_search(arr, key, left, mid, t);
    }
}

int binary_search_rotated(vector<int>& arr, int key) {
    // TODO: Write - Your - Code
    // normal condition
    int offset = get_offset(arr);
    function<int(int)> t = [=](int index) {
        return (index + offset) % arr.size();
    };
    int res = binary_search(arr, key, 0, arr.size(), t);
    if (res >= 0)
        return t(res);
    return -1;
}
Editor is loading...