Documente Academic
Documente Profesional
Documente Cultură
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.
The searching technique used here is binary search which is fast technique :
#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):
C Binary Search
Java Binary Search
C++ Online Test
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