i want to share with you my impl for binary search algo
my idea is to check not just the mid element but first & last elements every time before we check the mid one, so if any of first or last have the value needed there is no need to loop and divide searching for mid anymore. i think this way take less execution time, is it true or not? and why (if not) ?
#include<bits/stdc++.h>
using namespace std;
main()
{
vector<int> v(100000); int n;
sort(v.begin(),v.begin()+n);
int first =0; int last= n-1;
int mid; int idx=-1;
int x; cin>>x;
while(first<=last)
{
if(x==v[last] || x== v[first])
{
idx=x==v[last]?last:first;
break;
}
else
{
mid= first+(last-first)/2;
if(v[mid]<x) first=mid+1;
else if (v[mid]>x) last=mid-1;
else if (v[mid]==x)
{
idx=mid;
break;
}
}
}
if(idx ==-1) cout<<"NOT FOUND";
else cout<< idx;
}
it will return the last occurrence of the element if the element is found in the first or last position