CPP
CPP Notes
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
2. O/p when element not found
Binary Search in C++
08 July
0
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 FoundMust Read :-
- Blogger Tutorial
- C Programs
- C++ Programs
- Java Programs
- Python Programs
- Programming Notes
- Questions & Answers
- My Codes : HTML, CSS & JS
- All Subject Notes
Previous article
Next article
Leave Comments
Post a Comment