Advertisement
YouKnowWho07

Recursion Binary Search

Sep 6th, 2023
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.28 KB | None | 0 0
  1. #include <iostream>
  2.  
  3. int binarySearchRecursive(int arr[], int target, int left, int right) {
  4.     if (left > right) {
  5.         return -1; // Base case: Element not found
  6.     }
  7.  
  8.     int mid = left + (right - left) / 2;
  9.  
  10.     if (arr[mid] == target) {
  11.         return mid; // Base case: Element found at index 'mid'
  12.     } else if (arr[mid] < target) {
  13.         // If target is in the right half, search the right subarray
  14.         return binarySearchRecursive(arr, target, mid + 1, right);
  15.     } else {
  16.         // If target is in the left half, search the left subarray
  17.         return binarySearchRecursive(arr, target, left, mid - 1);
  18.     }
  19. }
  20.  
  21. int main() {
  22.     int arrSize;
  23.     std::cout << "Enter the size of the array: ";
  24.     std::cin >> arrSize;
  25.  
  26.     int arr[arrSize];
  27.     std::cout << "Enter sorted elements of the array: ";
  28.     for (int i = 0; i < arrSize; ++i) {
  29.         std::cin >> arr[i];
  30.     }
  31.  
  32.     int target;
  33.     std::cout << "Enter the target element to search for: ";
  34.     std::cin >> target;
  35.  
  36.     int result = binarySearchRecursive(arr, target, 0, arrSize - 1);
  37.  
  38.     if (result != -1) {
  39.         std::cout << "Element found at index: " << result << std::endl;
  40.     } else {
  41.         std::cout << "Element not found in the array." << std::endl;
  42.     }
  43.  
  44.     return 0;
  45. }
  46.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement