fork download
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. int lowerBound(int arr[], int n, int key){
  6. int low = 0;
  7. int high = n;
  8. while(low < high){
  9. int mid =(low + high) / 2;
  10. if(arr[mid] < key){
  11. low = mid + 1;
  12. }
  13. else{
  14. high = mid;
  15. }
  16. return low;
  17. }
  18. }
  19.  
  20.  
  21. int upperBound(int arr[], int n, int key){
  22. int low = 0;
  23. int high = n;
  24. while(low < high){
  25. int mid = (low + high) / 2;
  26. if(arr[mid] <= key){
  27. low = mid + 1;
  28. }
  29. else{
  30. high = mid;
  31. }
  32. return low;
  33. }
  34. }
  35.  
  36.  
  37. int main(){
  38. int arr[] = {1, 3, 3, 3, 4};
  39. cout << lowerBound(arr, 5, 4) << endl << upperBound(arr, 5, 4);
  40.  
  41. return 0;
  42. }
  43.  
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
3
3