Binary serch algo

 avatar
user_6075971
plain_text
2 years ago
782 B
0
Indexable
Never
#include <iostream>
using namespace std;
int binary_serch(int arr[], int n, int k)
{
    int s = 0;
    int e = n - 1;
    int mid = (s + e) / 2;
    while (s < e)
    {
        if (arr[mid] ==k)
        {
           return mid;
        }
        else if (arr[mid] < k)
        {
            s = mid + 1;
        }
        else 
        {
            e=mid-1;
        }
        mid=(s+e)/2;
    }
    
}
int main()
{
    int arr[100];
    int n;
    cout << "ENTER THE ARRAY SIZE--->";
    cin >> n;
    for (int i = 0; i < n; i++)
    {
        cin >> arr[i];
    }
    for (int i = 0; i < n; i++)
    {
        cout << arr[i] << "  ";
    }
    cout<<endl;
    int k;
    cout<<"ENTER THE KEY--->";
    cin>>k;
   cout<< "YOUR INDEX IS--->"<<binary_serch(arr,n,k);
    return 0;
}