Sunteți pe pagina 1din 3

codescracker main buttonbutton

C++ Program Binary Search

« Previous ProgramNext Program »


Binary Search in C++
To perform binary search or to search an element using binary search in C++ Programming,
you have to ask to the user to enter the array size then ask to enter the array elements.

Now ask to enter an element that is going to be search to start searching that element using
binary search technique and display the position of the element on the screen if found as shown
here in the following program.

C++ Programming Code for Binary Search


Following C++ program first ask to the user to enter "how many element he/she want to store in
array", then ask to enter the array elements. After storing the element in the array, program ask
to the user to enter the element which he/she want to search in the array whether that number is
present or not.

The searching technique used here is binary search which is fast technique :

/* C++ Program - Binary Search */

#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int n, i, arr[50], search, first, last, middle;
cout<<"Enter total number of elements :";
cin>>n;
cout<<"Enter "<<n<<" number :";
for (i=0; i<n; i++)
{
cin>>arr[i];
}
cout<<"Enter a number to find :";
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<<"Not found! "<<search<<" is not present in the list.";
}
getch();
}
When the above C++ program is compile and executed, it will produce the following result.
Above C++ Programming Example Output (Element found):

binary search c++ programming


Above C++ Programming Example Output (Element Not found):

c++ binary search program


Same Program in Other Language
You may like the same program in other programming languages:

C Binary Search
Java Binary Search
C++ Online Test

« Previous ProgramNext Program »


FacebookWhatsAppTwitterShare

enter email id
Tools
Calculator

Quick Links
Signup - Login - Give Online Test

Top Tutorials
Java Tutorial
C++ Tutorial
HTML Tutorial
PHP Tutorial
Python Tutorial
Computer Network Tutorial
Operating System Tutorial
Online Tests
All Test
Computer Fundamental Test
Java Test
C Test
C++ Test
HTML Test
PHP Test
Online Tests
Python Test
Operating System Test
Networking Test
Microsoft Word Test
Microsoft Excel Test
Computer Hardware Test
Linux Test
Examples
Java Examples
C Examples
C++ Examples
Python Examples
Join CodesCracker
Subscribe Us
Login
© Copyright 2019. All Rights Reserved.

CodesCracker

S-ar putea să vă placă și