Given a sorted array of data with lower bound LB and upper bound UB, and items is a given item of information. Using variables BEG,END and MID to denote, respectively,the beginning end and middle locations of a segment of elements of Data. Write a c++ program which finds the location LOC if item in DATA or sets LOC=NULL
#include <iostream.h>
#include <conio.h>
using namespace std;
class binary
{
int b, e, m, a[20], n, s, k, j, i, t;
public:
void read()
{
cout << "Enter the number of elements : ";
cin >> n;
cout << "\nEnter the elements : ";
for (i = 1; i <= n; i++)
{
cin >> a[i];
}
cout << "Sorted array is \n";
for (k = 1; k <= n; k++)
{
for (j = 1; j <= n; j++)
{
if (a[j] > a[j+1])
{
t = a[j];
a[j] = a[j+1];
a[j+1] = t;
}
}
}
}
void display()
{
for (i = 0; i<= n; i++)
{
cout << a[i] << "\t";
}
}
void search()
{
cout << "\nEnter the element to search : ";
cin >> s;
b = 1;
e = n;
m = ((b + e) / 2);
while ((b <= e) && (a[m] != s))
{
if (s < a[m])
{
e = m - 1;
}
else
{
b = m + 1;
}
m = ((b + e) / 2);
}
if (a[m] == s)
{
cout << s << " found in position " << m;
}
else
{
cout << "Element not founded : ";
}
}
};
int main()
{
clrsrc();
binary b;
b.read();
b.display();
b.search();
getch();
}
Comments
Leave a comment