Professional Documents
Culture Documents
1. 'arr' is the given array, 'lowerbound' is the index of the first array element, 'upper
bound' is the index of the last array element, 'k' is the value to search
2. Step 1: set s= lower_bound, e = upper_bound
3. Step 2: while s <=e
4. Step 3: set mid = (s + e)/2
5. Step-5: if(arr[mid]=k)
Return mid+1;
else if arr[mid] > k
set end = mid - 1
else
set beg = mid + 1
6. Step-6 mid=-1
Return -1;
7. Step-7 exit
4. CODE
#include<bits/stdc++.h>
using namespace std;
int binary(int arr[],int n,int k)
{
int s=0,e=n-1;
while(s<=e)
{ int mid=(s+e)/2;
if(arr[mid]==k)
{
return mid+1;
}
else if(arr[mid]>k){
e=mid-1;
}
else{
s=mid+1;
}
}
return -1;
}
int main()
{
int n,k;
cout<<"\nEnter how many elements u want to entered\n";
cin >> n;
cout<<"enter the element:\n";
int array[n];
for(int i = 0; i < n; i++){
cin >> array[i];
}
cout<<"Elements u want to search\n";
cin>>k;
cout<<"SORTED ELEMENTS ARE:\n";
sort(array,array+n);
for(int i = 0; i < n; i++){
cout<<array[i]<<" ";
}
cout<<endl;
cout<<"elements present at position is:";
cout<<binary(array,n,k);
return 0;
}
OUTPUT:-