fork download
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4. struct less_than_k {
  5. int k;
  6. less_than_k(int x) : k(x) {}
  7. bool operator() (int m,vector<int> &v) { return v[m]<k;}
  8. // this assumes that the above condition is true for the first part of the range [l,r)
  9. // and it is false for the remaining part the search will return the first element
  10. // in the search space which gives false for above condition
  11.  
  12. // Hence, above condition maps as the follow over the search space
  13. // t t t t t t t t t t t t t t t t f f f f f f f f f f
  14. // function will find the index of ^ element
  15. };
  16. struct less_than_equal_k {
  17. int k;
  18. less_than_equal_k(int x) : k(x) {}
  19. bool operator() (int m,vector<int> &v) { return v[m]<=k;}
  20. };
  21. template <class T, class Comp>
  22. int binarySearch(int l, int r, Comp comp, T& t){
  23. int m = l+(r-l)/2;
  24. while(l<r){
  25. if(comp(m,t)) l = m+1;
  26. else r = m;
  27. m = l+(r-l)/2;
  28. }
  29. return m;
  30. }
  31. int binarySearch(vector<int> &a, int k, bool strict = false){
  32. if(strict) return binarySearch(0,a.size(),less_than_equal_k(k),a);
  33. return binarySearch(0,a.size(),less_than_k(k),a);
  34. }
  35. int main() {
  36. vector<int> a = {1,1,3,3,3,3,4,4,4,5,5};
  37. cout<<"4th index is less than 2: "<<less_than_k(2)(4,a)<<endl;
  38. cout<<"6th index is less than equal 4: "<<less_than_equal_k(4)(6,a)<<endl;
  39.  
  40. cout<<"Size of array is "<<binarySearch(a,6)<<endl;
  41. cout<<"Count of 3 in array is "<<binarySearch(a,3,true)-binarySearch(a,3)<<endl;
  42. cout<<"Index of first 4 is "<<binarySearch(a,4,false)<<endl;
  43. cout<<"Index of last 4 is "<<binarySearch(a,4,true)-1<<endl;
  44. cout<<"Count of 2 in array is "<<binarySearch(a,2,true)-binarySearch(a,2)<<endl;
  45. return 0;
  46. }
Success #stdin #stdout 0s 4268KB
stdin
Standard input is empty
stdout
4th index is less than 2: 0
6th index is less than equal 4: 1
Size of array is 11
Count of 3 in array is 4
Index of first 4 is 6
Index of last 4 is 8
Count of 2 in array is 0