Binary Search in DSA C++

Program 1

//Binary  Search 
#include<iostream>
#include<stdio.h>
using namespace std;
int main()
{
    system("cls");  
    int ar[500],n,i,j,s,temp,low,high,mid,flag=0;
    cout<<"\n Enter the limit of array: ";
    cin>>n;
    cout<<"\n Enter elements in array: ";
    for(int i=0;i<n;i++)
    cin>>ar[i];
    // Sorting my array
    for(i=0;i<n;i++)
    {
         for(j=i+1;j<n;j++)
         {
             if(ar[j]<ar[i])
             {
                 temp=ar[i];
                 ar[i]=ar[j];
                 ar[j]=temp;
             }
         }
    }
    for(i=0;i<n;i++)
    {
        cout<<"\n"<<ar[i];
    }
  cout<<"\n Enter an element for search: ";
  cin>>s;
  low=0;
  high=n-1;
  while(low<=high)
  {
        mid=(low+high)/2;
        
        if(s==ar[mid])
        {
             flag=1;
             break;
        }
        if(s>ar[mid])
          low=mid+1;
       else
        high=mid-1;   
  }
  if(flag==1)
     cout<<"\n Searching success: ";
   else
      cout<<"\n Searching not success: "; 
}

 

courses
Image

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

Your email address will not be published. Required fields are marked *