hi, below is the code for binary search in case of array is sorted in ascending order.
what changes i have to do if array is sorted in descending order.
#include<iostream>
using namespace std;
void getdata (int a[], int size);
int binarysearch (int a[], int size, int key);
int main()
{
int size=10;
int a[size];
getdata (a, size);
int key=11;
int search=binarysearch (a, size, key);
if (search==-1)
cout<<"sorry, key is not found.";
else
cout<<"key is found at position " <<search <<endl;
return 0;
}
void getdata (int a[], int size)
{
for (int i=0; i<size; i++)
cin>>a[i];
}
int binarysearch (int a[], int size, int key)
{
int first=0;
int last=size-1;
int mid;
bool found=false;
while (first<=last && !found)
{
mid=(first+last)/2;
if (a[mid]==key)
found=true;
else if (a[mid]>key)
last=mid-1;
else
first=mid+1;
}
if (found)
return mid;
else
return -1;
}