Binary Search in C++



//Binary Search in 1D Array
#include<iostream>
#include<iomanip>
#include<time.h>
#include<stdlib.h>
using namespace std; 

void searchArray()
{
int i, n, arr[50], srch, mid, beg, last,flag=0;
cout<<"===============================\n";
cout<<"Binary Search in an array\n";
cout<<"===============================\n";
cout<<"Enter size of Array (Max. 50): ";
cin>>n;
srand((unsigned)time(NULL));
arr[0]=rand()%5+1;
for(i=1;i<n;i++)
{
arr[i]=rand()%5+arr[i-1]+1;
}
cout<<"Randomly Generated Sorted Array Values...\n";
for(i=0;i<n;i++)
{
cout<<setw(4)<<arr[i];
}
cout<<"\nEnter the number you want to search: ";
cin>>srch;
beg=0;
last=n-1;
while(beg<=last)
{
mid=(beg+last)/2;
if(srch==arr[mid])
{
cout<<"Number found at index no.: "<<mid<<endl;
flag++;
break;
}
else if(srch>arr[mid])
beg=mid+1;
else if(srch<=arr[mid])
last=mid-1;
}
if(flag==0)
cout<<"Number "<<srch<<" is not in array....\n";
}

int main()
{
searchArray();
}


Click to Watch Video

No comments

Post your comments

Powered by Blogger.