Data Structure Using C++
Array Data Structure
Searching
Binary Search
void binarySearch(int arr[],int key,int n);
int main()
{
int arr[10], i, j, key;
for(i=0;i<10;i++)
{
arr[i]=rand()%100;
}
cout<<"The unsorted array: ";
for(i=0;i<10;i++)
{
cout<<arr[i]<<" ";
}
cout<<"\nThe sorted array is: ";
for(i=0;i<10;i++)
{
for(j=i+1;j<10;j++)
{
if(arr[i]>arr[j])
{
int tmp=arr[i];
arr[i]=arr[j];
arr[j]=tmp;
}
}
cout<<arr[i]<<" ";
}
cout<<"\nEnter any number to find: ";
cin>>key;
binarySearch(arr,key,10);
}
void binarySearch(int arr[],int key,int n){
int s=0, m, e=9;
while(s<=e)
{
m=(s+e)/2;
if(key==arr[m])
break;
else if(key>arr[m])
s=m+1;
else
e=m-1;
}
if(s>e)
cout<<"Value not found.";
else
cout<<"Value found at : "<<m;
}
Let me know in the comment section if you have any question.
Previous Post:
Linear Search | Sequential Search In Data Structure Using C++
Next Post:
Comments
Post a Comment