Binary Search Explained

 

Binary Search


Binary Search is an algorithm that is basically used for finding a particular Key in the given array of N size.

Algorithm Steps for Binary Search are given below-

1- Find the mid value by using mid = ( start + end )/2;

2- Compare the Key, if Key = = arr[mid], then return the index i.e. in this case index is mid.

3- If Key ! = arr[mid], then decide whether key > arr[mid] or key < arr[mid],

4- Then update the mid again as, mid = ( start + end )/2;

5- Loop iteration will continue, in Incase

6- If the Key is not present then return -1;


C++ Program for Binary Search

#include<iostream>
using namespace std;
int Iskeypresent(int arr[], int n, int key)
{
    int s=0;
    int e=n-1;
    int mid=s+((e-s)/2);
    while(s<=e)
   
    {
        if(arr[mid]==key)
        {
            return mid;

        }

        if(key>arr[mid])
        {
            s=mid+1;

        }
        else
        {
            e=mid-1;

        }
        mid= s+((e-s)/2);

    }
    return -1;


}
int main()

{

    int arr[10]={1,4,6,7,9,10,45,63,65,100};

    int index= Iskeypresent(arr,10,1001);
    cout<<index;


   


}


if ( This Post was Helpful )

{   

      <<"Do Share it with Your Friends and Classmates">>

}

return Comments and Likes;

Post a Comment

0 Comments