Question 1 - Binary Search

 avatar
itsLu
c_cpp
2 months ago
1.1 kB
24
Indexable
Never
// 1. Write a function to search for a number in a sorted
// array using binary search algorithm.


#include <iostream>
using namespace std;

int BinarySearch (int arr[], int n, int key)
{
    int low = 0, high = n - 1, mid;
    while (low <= high)
    {
        mid = (low+high)/2;
        if (key == arr[mid])
            return mid;
        else if (key < arr[mid])
            high = mid - 1;
        else
            low = mid + 1;
    }
    return -1;
}

int RecBinarySearch (int arr[], int low, int high, int key)
{
    if (high < low)
        return -1;
    int mid = (low+high)/2;
    if (key == arr[mid])
        return mid;
    else if (key < arr[mid])
        RecBinarySearch(arr, low, mid - 1, key);
    else
        RecBinarySearch(arr, mid + 1, high, key);
}

int main()
{
    int arr[5] = {1, 2, 3, 4 ,5}, n = 5, key, res;
    cout << "Please enter key to search: ";
    cin >> key;
    res = RecBinarySearch(arr, 0, n - 1, key);
    if (res == -1)
        cout << key << " was not found!";
    else
        cout << key << " was found in index " << res;
}
Leave a Comment