Binary Search in C++ without using Function with Random and Randomize Function

//Binary Search without user defined functions with random & randomize function

#include<iostream.h>
#include<conio.h>
#include<stdlib.h>

void main()
{
int a[20], i, n, srch, beg, end, mid, flag=0;
clrscr();

cout<<"Enter the number of values you want to store in array (Max. 20): ";
cin>>n;

a[0]=random(20)+5;
cout<<a[0]<<"\t";

randomize();
for(i=1;i<n;i++)
{
a[i]=random(20)+a[i-1]+1;
cout<<a[i]<<"\t";
}
cout<<endl;

cout<<"Enter the number you want to search : ";
cin>>srch;
beg=0;
end=n-1;

while(beg<=end)
{
mid=(beg+end)/2;
if(a[mid]==srch)
{
cout<<"Number "<<srch<<" found at "<<mid+1<<" position.\n";
flag++;
break;
}
else if(srch>a[mid])
{
beg=mid+1;
}
else if(srch<a[mid])
{
end=mid-1;
}
}

if(flag==0)
{
cout<<"The number "<<srch<<" not in an array\n";
}
getch();
}

/*
Output
Enter the number of values you want to store in array (Max. 20): 10
5       14      34      53      58      77      88      94      106     126

Enter the number you want to search : 77
Number 77 found at 6 position.
*/


No comments

Post your comments

Powered by Blogger.