Advertisement
shabbyheart

high bound

Mar 17th, 2019
222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.16 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3. /**int high_bound(int arr[],int n,int k)
  4. {
  5.     int low=0,high=n-1,ans=-1;
  6.     while(low<=high)
  7.     {
  8.         int middle=(low+high+1)/2;
  9.         if(k==arr[middle])
  10.         {
  11.             ans=middle;
  12.             low=middle+1;
  13.         }
  14.         else if(k>arr[middle])
  15.             low=middle+1;
  16.         else
  17.             high=middle-1;
  18.     }
  19.     return ans;
  20. }
  21. int main()
  22. {
  23.     int arr[7]={1,2,2,2,3,4,5};
  24.     cout<<"Higher bound is: "<< high_bound(arr,7,2);
  25. }**/
  26.  
  27. vector<int>vec;
  28. void uperBound(int k)
  29. {
  30.     int low=0,high=vec.size()-1,ans=-1;
  31.     while(low<=high)
  32.     {
  33.         int mid=(low+high+1)/2;
  34.         if(k==vec[mid])
  35.         {
  36.             ans=mid;
  37.             low=mid+1;
  38.         }
  39.         else if(k>vec[mid])
  40.             low=mid+1;
  41.         else
  42.             high=mid-1;
  43.     }
  44.     cout<<ans;
  45. }
  46. int main()
  47. {
  48.     int n,k;
  49.     cout<<"Enter how many Element"<<endl;
  50.     cin>>n;
  51.     cout<<"Enter values"<<endl;
  52.     while(n--)
  53.     {
  54.         int value;
  55.         cin>>value;
  56.         vec.push_back(value);
  57.     }
  58.     cout<<"which value you want to search";
  59.     cin>>k;
  60.     uperBound(k);
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement