This Post Contains A C++ Program To Perform Binary Search. With Correct Source Code & Output. This Program Is Written, Compiled & Executed At TurboC/C++3.0 Compiler & Will Help You To Understand The Concept Of 'Binary Search' From C++ Language. It Is A Well-Structured Program With Proper Comments Which Provides Step-By-Step Description Of Various Features Of The Language In A Simple & Easy-To-Understand Way.
# Note : You Can Simply Copy-Paste The Following Program Or Code Into Compiler For Direct Result.
C++ Program To Perform Binary Search.
/* Declaration Of Header Files */
#include<iostream.h>
#include<conio.h>
/* Start Of Main Program */
void main()
{
/* Declaration Of Variables */
int i, j, x, dim, temp;
int low=0, high=0, mid=0;
int a[20];
clrscr();
/* Asking For The Input From User */
cout<<" \n Enter Dimension : ";
cin>>dim;
cout<<" \n Enter Values For Array : ";
for(i=0;i<dim;i++)
{
cin>>a[i];
}
// For Searching Values, They Should Be Sorted First.
// Sorting Values In Ascending Order.
for(i=0;i<dim;i++)
{
for(j=i+1;j<dim;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
// Printing Values Of Array 'a' After Sorting.
cout<<" \n Sorted Array Is : ";
for(i=0;i<dim;i++)
{
cout<<a[i]<<"\t";
}
/* Source Code For Computing Binary Search */
cout<<" \n Enter Value To Be Searched : ";
cin>>x;
low=0;
high=dim;
while(low<=high)
{
mid=(low+high)/2;
if(x<a[mid])
{
high=mid-1;
}
else
{
if(x>a[mid])
{
low=mid+1;
}
else
{
if(x==a[mid])
{
cout<<x<<" Is Located At Location "<<mid+1;
break;
}
}
}
}
getch();
}
Output :
Enter Dimension : 5
Enter 5 Values :
44 22 11 55 33
Sorted Array Is :
11 22 33 44 55
Enter Value To Be Searched : 33
33 Is Located At Location 3
# Note : You Can Simply Copy-Paste The Following Program Or Code Into Compiler For Direct Result.
C++ Program To Perform Binary Search.
/* Declaration Of Header Files */
#include<iostream.h>
#include<conio.h>
/* Start Of Main Program */
void main()
{
/* Declaration Of Variables */
int i, j, x, dim, temp;
int low=0, high=0, mid=0;
int a[20];
clrscr();
/* Asking For The Input From User */
cout<<" \n Enter Dimension : ";
cin>>dim;
cout<<" \n Enter Values For Array : ";
for(i=0;i<dim;i++)
{
cin>>a[i];
}
// For Searching Values, They Should Be Sorted First.
// Sorting Values In Ascending Order.
for(i=0;i<dim;i++)
{
for(j=i+1;j<dim;j++)
{
if(a[i]>a[j])
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
// Printing Values Of Array 'a' After Sorting.
cout<<" \n Sorted Array Is : ";
for(i=0;i<dim;i++)
{
cout<<a[i]<<"\t";
}
/* Source Code For Computing Binary Search */
cout<<" \n Enter Value To Be Searched : ";
cin>>x;
low=0;
high=dim;
while(low<=high)
{
mid=(low+high)/2;
if(x<a[mid])
{
high=mid-1;
}
else
{
if(x>a[mid])
{
low=mid+1;
}
else
{
if(x==a[mid])
{
cout<<x<<" Is Located At Location "<<mid+1;
break;
}
}
}
}
getch();
}
Output :
Enter Dimension : 5
Enter 5 Values :
44 22 11 55 33
Sorted Array Is :
11 22 33 44 55
Enter Value To Be Searched : 33
33 Is Located At Location 3
No comments:
Post a Comment