Binary Search in C++ - 👑 सार्थक मुंड S3 🤴🏻

Binary Search in C++

Binary Search in C++

Binary Search in C++ :-

   Binary search is the most popular Search algorithm.It is efficient and also one of the most commonly used techniques that is used to solve problems. If all the names in the world are written down together in order and you want to search for the position of a specific name, binary search will accomplish this in a maximum of iterations. 
   The idea of binary search is to use the information that the array is sorted and reduce the time complexity to O(Log n). The linear search method discussed so far is treated as the simplest search method and works fine if the lists are small. If the list is very large, then they lead to  inefficient search methods.

C++ Program for Binary Search :-

#include<iostream.h>
#include<conio.h>
void main()
{
    clrscr();
    int n, i, arr[50], search, first, last, middle;
    cout<<"Enter the Size of Array :\n";
    cin>>n;
    cout<<"Enter "<<n<<" elements of Array :\n";
    for (i=0; i<n; i++)
    {
         cin>>arr[i];
    }
    cout<<"Enter the number to be Find :\n";
    cin>>search;
    first = 0;
    last = n-1;
    middle = (first+last)/2;
    while (first <= last)
    {
        if(arr[middle] < search)
        {
              first = middle + 1;
        }
       else if(arr[middle] == search)
       {
              cout<<search<<" found at location : "<<middle+1<<"\n";
              break;
       }
       else
       {
              last = middle - 1;
        }
    middle = (first + last)/2;
    }
    if(first > last)
   {
    cout<<"Number Not found..!  "<<search<<"  is not present in the list.";
    }
getch();
}

OutPut :-

1. O/p when Element Found
Binary Search in C++


2. O/p when element not found
Binary Search in C++

Must Read :-

  1. Blogger Tutorial
  2. C Programs
  3. C++ Programs
  4. Java Programs
  5. Python Programs
  6. Programming Notes 
  7. Questions & Answers
  8. My Codes : HTML, CSS & JS
  9. All Subject Notes 

Previous article
Next article

Leave Comments

Post a Comment

Articles Ads

Articles Ads 1

Articles Ads 2

Advertisement Ads