Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

C++ program for binary search

This code implements binary search in c ++language. It can only be used for sorted arrays, but it's fast as compared to linear search. If you wish to use binary search on an array which is not sorted then you must sort it using some sorting technique say merge sort and then use binary search algorithm to find the desired element in the list. If the element to be searched is found then its position is printed.
Source Code:-

#include <iostream.h>
#include <conio.h>
void main()
{  clrscr();
   int c, first, last, middle, n, search, array[100];
   cout<<"Program for Binary Search by-Tarun Rawat\n";
   cout<<"\nEnter number of elements : ";
   cin>>n;
   cout<<"Enter "<<n<<" integers \n";
   for ( c = 0 ; c < n ; c++ )
cin>>array[c];

   cout<<"\nEnter value to find it's location\n";
   cin>>search;
   first = 0;
   last = n - 1;
   middle = (first+last)/2;
   while( first <= last )
   { if ( array[middle] < search )
first = middle + 1;
      else if ( array[middle] == search )
      {
cout<<search<<" found at location "<< middle+1;
break;
      }
      else
last = middle - 1;
middle = (first + last)/2;
   }
   if ( first > last )
      cout<<"Not found! "<<search<<"  is not present in the list.\n";
getch();
}

No comments:

Post a Comment

Blogger Widgets

Find Us On Google, Just type - way2cplusplus -

If you have any questions on implementing or understanding this C++ Program , shoot me a comment and I'll be glad to help! :) :)