Design an algorithm to implement binary lookup, very simple problem. Here is a list of recursive and non-recursive
Recursive implementation
#include <iostream>
#include <cstdio>
#include <ctime>
#include <cstdlib>
#include <stack>
#include <algorithm>
#include <queue>
using namespace std;
int n,a[105];
int search_bin (int stat,int end,int tmp)
{
int i,j;
if (stat>end)
return-1;
if (stat==end)
{
return stat;
}
if (tmp==a[(stat+end)/2])
{
return (stat+end)/2;
}
if (tmp>a[(stat+end)/2])
{
return Search_bin ((stat+end)/2+1,end,tmp);
}
else if (tmp<a[(stat+end)/2])
{
return Search_bin (Stat, (stat+end)/2-1,tmp);
}
}
int main ()
{
int i,j,tmp;
printf ("Please enter the number of numbers you want to randomly generate \ n");
scanf ("%d", &n);
Srand (Time (0));
for (i=0;i<n;i++)
{
a[i]=rand ()%1000;
}
Sort (a,a+n);
printf ("The answer after the randomly generated number is \ n");
for (i=0;i<n;i++)
{
printf ("%d", A[i]);
}
printf ("\ n");
printf ("Please enter the number you are looking for \ n");
scanf ("%d", &tmp);
printf ("The number is located at%d \ n", Search_bin (0,n-1,tmp) +1);
return 0;
}
Non-recursive implementation
#include <iostream>
#include <cstdio>
#include <ctime>
#include <cstdlib>
#include <stack>
#include <algorithm>
#include <queue>
using namespace std;
int n,a[105];
int search_bin (int stat,int end,int tmp)
{
int i,j;
printf ("Where the number is located");
while (Stat<=end)
{
if (stat==end)
{
printf ("%d\n", stat+1);
break;
}
if (tmp==a[(stat+end)/2])
{
printf ("%d\n", stat+1);
break;
}
if (tmp>a[(stat+end)/2])
stat= (stat+end)/2+1;
else if (tmp<a[(stat+end)/2])
end= (stat+end)/2-1;
}
}
int main ()
{
int i,j,tmp;
printf ("Please enter the number of numbers you want to randomly generate \ n");
scanf ("%d", &n);
Srand (Time (0));
for (i=0;i<n;i++)
{
a[i]=rand ()%1000;
}
Sort (a,a+n);
printf ("The answer after the randomly generated number is \ n");
for (i=0;i<n;i++)
{
printf ("%d", A[i]);
}
printf ("\ n");
printf ("Please enter the number you are looking for \ n");
scanf ("%d", &tmp);
Search_bin (0,n-1,tmp) +1;
printf ("The number is located at%d \ n", Search_bin (0,n-1,tmp) +1);
return 0;
}