fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. //UPPER BOUND OF ANY NUMBER IS A NUMBER WHICH IS CLOSER TO TARGET BUT GREATER NOT SMALLER
  4. int UPPERBOUND(const vector<int>&v,int k){
  5. int n=v.size();
  6. int l=0,r=n-1,ans=n;
  7.  
  8. while(l<=r){
  9. int mid=l+(r-l)/2;
  10. if(v[mid]>k){
  11. ans=mid;
  12. r=mid-1;
  13. }else{
  14. l=mid+1;
  15. }
  16. }
  17. return ans;
  18. }
  19. int main(){
  20. cout<<"Enter Size of the array-";
  21. int n;cin>>n;cout<<endl;
  22. cout<<"Enter elements in asending order"<<endl;
  23. vector<int>v(n);
  24. for(int i=0;i<n;i++)cin>>v[i];
  25. cout<<"Enter Target value- ";int t;cin>>t;cout<<endl;
  26. int a=UPPERBOUND(v,t);
  27. cout<<"Index:"<<a<<endl;
  28.  
  29. }
Success #stdin #stdout 0.01s 5288KB
stdin
5
11 22 33 44 55
42
stdout
Enter Size of the array-
Enter elements in asending order
Enter Target value- 
Index:3