recursive binary search in sorted array

 avatar
user_9350232
plain_text
9 months ago
1.1 kB
11
Indexable
#include <iostream>
using namespace std;

// Recursive Binary Search Function
int binarySearch(int arr[], int low, int high, int key) {
    if (low > high)
        return -1;  // Element not found

    int mid = (low + high) / 2;

    if (arr[mid] == key)
        return mid;  // Element found
    else if (arr[mid] > key)
        return binarySearch(arr, low, mid - 1, key);  // Search left part
    else
        return binarySearch(arr, mid + 1, high, key); // Search right part
}

int main() {
    int n, key;

    cout << "Enter number of elements: ";
    cin >> n;

    int arr[n];
    cout << "Enter elements in sorted order:\n";
    for (int i = 0; i < n; i++)
        cin >> arr[i];

    cout << "Enter element to search: ";
    cin >> key;

    int result = binarySearch(arr, 0, n - 1, key);

    if (result != -1)
        cout << "Element found at index: " << result << endl;
    else
        cout << "Element not found in the array.\n";

    cout << "\nTime Complexity: O(log n)\nSpace Complexity: O(log n)\n";
    return 0;
}
Editor is loading...
Leave a Comment