Iterator binary_search_helper(Iterator begin, Iterator end, const ValueType& value, Iterator not_found) { if(begin == end) { return not_found; } auto distance = std::distance(begin, end); auto it = begin + distance/2; if(value < *it) { return binary_search_helper(begin, it, value, not_found); } else if (*it < value) { return binary_search_helper(it+1, end, value, not_found); } else { return it; } }
static int binary_search_helper(int key, int arr[], int start_index, int end_index) { int middle; if (start_index > end_index) { return -1; } binary_search_test_debug_stat(); middle = (start_index + end_index) / 2; if (key == arr[middle]) { return middle; } else if (key < arr[middle]) { return binary_search_helper(key, arr, start_index, middle - 1); } else { return binary_search_helper(key, arr, middle + 1, end_index); } }
static int binary_search(int key, int arr[], int length) { return binary_search_helper(key, arr, 0, length - 1); }
Iterator recursive_binary_search(Iterator begin, Iterator end, const ValueType& value) { return binary_search_helper(begin, end, value, end); }