Program in c++ for BINARY SEARCH...
DESCRIPTION:- A binary search finds the position of a specified input value within an array sorted by key value.In each step, the algorithm compares the search key value with the key value of the middle element of the array. If the keys match, then a matching element has been found and its index, or position, is returned. Otherwise, if the search key is less than the middle element's key, then the algorithm repeats its action on the sub-array to the left of the middle element or, if the search key is greater, on the sub-array to the right. If the remaining array to be searched is empty, then the key cannot be found in the array and a special "not found" indication is returned.
OUTPUT OF THE PROGRAM:-
SOURCE CODE:-
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int arr[5]={1,2,3,4,5};
int beg,end,mid,num;
int flag=0;
cout<<"\nEnter number to search:";
cin>>num;
beg=0;
end=4;
mid=(beg+end)/2;
while(beg<=end && arr[mid]!=num)
{
if(num>arr[mid])
{
beg=mid+1;
}
else
{
end=mid-1;
}
mid=(beg+end)/2;
}
if(arr[mid]==num)
{
cout<<"\nNumber found";
}
else
cout<<"\nNOt found";
getch();
}
/*
THANKU.
DESCRIPTION:- A binary search finds the position of a specified input value within an array sorted by key value.In each step, the algorithm compares the search key value with the key value of the middle element of the array. If the keys match, then a matching element has been found and its index, or position, is returned. Otherwise, if the search key is less than the middle element's key, then the algorithm repeats its action on the sub-array to the left of the middle element or, if the search key is greater, on the sub-array to the right. If the remaining array to be searched is empty, then the key cannot be found in the array and a special "not found" indication is returned.
OUTPUT OF THE PROGRAM:-
SOURCE CODE:-
#include<iostream>
#include<conio.h>
using namespace std;
int main()
{
int arr[5]={1,2,3,4,5};
int beg,end,mid,num;
int flag=0;
cout<<"\nEnter number to search:";
cin>>num;
beg=0;
end=4;
mid=(beg+end)/2;
while(beg<=end && arr[mid]!=num)
{
if(num>arr[mid])
{
beg=mid+1;
}
else
{
end=mid-1;
}
mid=(beg+end)/2;
}
if(arr[mid]==num)
{
cout<<"\nNumber found";
}
else
cout<<"\nNOt found";
getch();
}
/*
THANKU.
0 comments:
Post a Comment