Binary search in C++

 #include<iostream>

using namespace std;

int main()

{

int i,found=0,num,n,arr[100],mid,low,high// declaration and initialization of variables

cout<<"enter the size of array\n";   //prints the msg in double colon

cin>>n;   //stores the value in n

for(i=0;i<n;i++)   //for loop

{

cout<<"\n arr["<<i<<"] = ";      //for block

cin>>arr[i];      //for block

}

cout<<"Enter number to be search\n";  //prints the msg in double colon

cin>>num;   //stores the value in n

low=0;   //initialization of low  to 0

high=n-1;   //initialization of high to n-1

while(low<=high)    //while loop

{

mid=(low+high)/2;

if(arr[mid]==num)

{

cout<<"Enter element is found";

break;

}

else if(num<arr[mid])

{

high=mid-1;

}

else

{

low=mid+1;

}

}

if(low>high&&found==0)

cout<<"\nEnter number is not found";

else if(found==1)

cout<<"Enter mumber is found";

}

Output:

enter the size of array

5


 arr[0] = 5


 arr[1] = 3


 arr[2] = 4


 arr[3] = 2


 arr[4] = 1

Enter number to be search

6

Comments