Advertisement
AnindyaBiswas

AtLeast AtMost

Aug 24th, 2024
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.86 KB | None | 0 0
  1. #include<iostream>
  2. using namespace std;
  3.  
  4. int A[] = {1,2,3,4,5,6,7};
  5.  
  6.  
  7. int SearchAtLeast(int x){
  8.     int left = 0, right = sizeof(A)/sizeof(A[0]), mid = 0, result = -1;
  9.  
  10.     while(left < right)
  11.     {
  12.         mid = (left + right)/2;
  13.         if(A[mid] >= x){
  14.              result = mid;    
  15.             right = mid - 1;
  16.         }
  17.         else {
  18.             left = mid + 1;  
  19.         }
  20.     }
  21.  
  22.     return result;
  23. }
  24.  
  25. int SearchAtMost(int x){
  26.     int left = 0, right = sizeof(A)/sizeof(A[0]), mid = 0, result = -1;
  27.  
  28.     while(left < right)
  29.     {
  30.         mid = (left + right)/2;
  31.         if(A[mid] <= x){
  32.              result = mid;    
  33.             left = mid + 1;  
  34.         }
  35.         else {
  36.             right = mid - 1;
  37.         }
  38.     }
  39.  
  40.     return result;
  41. }
  42.  
  43.  
  44.  
  45. int main(){
  46.     cout<<SearchAtLeast(-2)<<endl;
  47.     cout<<SearchAtMost(10)<<endl;
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement