fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. int BinaryS(vector<int>&v,int target){
  4. int n=v.size();
  5. int l=0,r=n-1;
  6. while(r>l){
  7. int mid= (l+r)/2;
  8. if(v[mid]==target){
  9. return mid+1;
  10. }else if(v[mid]>target){
  11. r=mid-1;
  12. }else{
  13. l=mid+1;
  14. }
  15. }
  16. return -1;
  17. }
  18. int main(){
  19. cout<<"Enter Size of the array-";
  20. int n;cin>>n;cout<<endl;
  21. cout<<"Enter elements in asending order"<<endl;
  22. vector<int>v(n);
  23. for(int i=0;i<n;i++)cin>>v[i];
  24. cout<<"Enter Target value- ";int t;cin>>t;cout<<endl;
  25. int a=BinaryS(v,t);
  26. if(a==-1){
  27. cout<<"The element "<<t<<" do not exist in the array"<<endl;
  28. }else{
  29. cout<<"Index:"<<a<<endl;
  30. }
  31. }
Success #stdin #stdout 0s 5320KB
stdin
5
1 12 41 66 384
66
stdout
Enter Size of the array-
Enter elements in asending order
Enter Target value- 
Index:4