Advertisement
Imran_Mohammed

Binary_Search

Feb 1st, 2021
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.59 KB | None | 0 0
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4.  
  5.     int main()
  6.     {
  7.         //Binary Search: Complexity log2(n)
  8.         //linear search complexity 0(n)
  9.         int a[] = {1,2,3,4,5,6,7,8,10,12};
  10.         int n=10;
  11.         int target = 10;
  12.         int l=0,r=n-1;
  13.         bool done = 0;
  14.  
  15.         while(l<=r){
  16.             int mid = (l+r)/2;
  17.             if(a[mid] == target){
  18.                 cout << mid << endl;//Index 8
  19.                 done =1;
  20.                 break;
  21.             }
  22.  
  23.             else if(a[mid] <target){
  24.                 l = mid+1;
  25.             }
  26.             else{
  27.                 r = mid-1;
  28.             }
  29.         }
  30.         if(!done)cout << "not found" << endl;
  31.  
  32.         //Binary search by using function:
  33.         vector <int> v={1,2,3,4,5};
  34.         cout << binary_search(v.begin(),v.end(),4) << endl;//1 (if not found output 0)
  35.  
  36.         //lower bond , upper bound:(how many elements lower and upper , where sorted)
  37.         vector < int > v1 ={2,3,3,3,4,4,5};
  38.         int lo= lower_bound(v1.begin(),v1.end(),3)-v1.begin();//1(1 element lower than 3)
  39.         int up= upper_bound(v1.begin(),v1.end(),3)-v1.begin();//4(3 elements upper than 3)
  40.         cout << lo << endl;
  41.         cout << up << endl;
  42.  
  43.         //Fractional Bisection:
  44.         long long int p;
  45.         double x,y;
  46.         cin >> p;
  47.         x=0,y=p;
  48.         for(int i=1; i<=100; i++){//or while(y-x >eps)
  49.             double mid = (x+y)/2.0;
  50.             if( (mid*mid) > p){
  51.                 y = mid;
  52.             }
  53.             else x = mid;
  54.         }
  55.         cout << floor(x) << endl;
  56.     return 0;
  57. }
  58.  
  59.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement