Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- int binarySearchRecursive(int arr[], int target, int left, int right) {
- if (left > right) {
- return -1; // Base case: Element not found
- }
- int mid = left + (right - left) / 2;
- if (arr[mid] == target) {
- return mid; // Base case: Element found at index 'mid'
- } else if (arr[mid] < target) {
- // If target is in the right half, search the right subarray
- return binarySearchRecursive(arr, target, mid + 1, right);
- } else {
- // If target is in the left half, search the left subarray
- return binarySearchRecursive(arr, target, left, mid - 1);
- }
- }
- int main() {
- int arrSize;
- std::cout << "Enter the size of the array: ";
- std::cin >> arrSize;
- int arr[arrSize];
- std::cout << "Enter sorted elements of the array: ";
- for (int i = 0; i < arrSize; ++i) {
- std::cin >> arr[i];
- }
- int target;
- std::cout << "Enter the target element to search for: ";
- std::cin >> target;
- int result = binarySearchRecursive(arr, target, 0, arrSize - 1);
- if (result != -1) {
- std::cout << "Element found at index: " << result << std::endl;
- } else {
- std::cout << "Element not found in the array." << std::endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement