#include <iostream.h>
#include<conio.h>
int BinarySearch(int [], int, int );
void main()
{
clrscr();
int n,i,arr[50],item,location;
cout<<"\nEnter Numbers of elements you have :\n";
cin>>n;
cout<<"\nEnter "<<n<<" Elements :\n";
for(i=0;i<n;i++)cin>>arr[i];
cout << "Enter the item you are searching for: ";
cin >> item;
location = BinarySearch(arr,n,item);
if (location > -1)
cout << "The item was found at index location "<< location+1;
else
cout << "The item was not found in the list\n";
getch();
}
int BinarySearch(int list[], int size, int key)
{
int left, right, midpt;
left = 0;
right = size-1;
while (left <= right)
{
midpt = (left + right) / 2;
if (key == list[midpt])
{
return midpt;
}
else if (key > list[midpt])
left = midpt + 1;
else
right = midpt - 1;
}
return -1;
}
#include<conio.h>
int BinarySearch(int [], int, int );
void main()
{
clrscr();
int n,i,arr[50],item,location;
cout<<"\nEnter Numbers of elements you have :\n";
cin>>n;
cout<<"\nEnter "<<n<<" Elements :\n";
for(i=0;i<n;i++)cin>>arr[i];
cout << "Enter the item you are searching for: ";
cin >> item;
location = BinarySearch(arr,n,item);
if (location > -1)
cout << "The item was found at index location "<< location+1;
else
cout << "The item was not found in the list\n";
getch();
}
int BinarySearch(int list[], int size, int key)
{
int left, right, midpt;
left = 0;
right = size-1;
while (left <= right)
{
midpt = (left + right) / 2;
if (key == list[midpt])
{
return midpt;
}
else if (key > list[midpt])
left = midpt + 1;
else
right = midpt - 1;
}
return -1;
}