Advertisement
vitormartinotti

busca_binária

Sep 6th, 2024
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.48 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define MAXN 50000
  3. #define _ ios_base::sync_with_stdio(0);cin.tie(0);
  4.  
  5. using namespace std;
  6.  
  7. int v[MAXN];
  8.  
  9. /*
  10. ---Busca Binária---
  11.  
  12. A função a seguir retorna uma posição de x em v, se x não estiver contido retorna -1.
  13.  
  14. OBS: Não funciona para obter a primeira ocorrência de x.
  15. */
  16.  
  17. int busca_binaria(int v[], int n, int x){
  18.     int l = 1;
  19.     int r = n;
  20.  
  21.     while(l <= r){
  22.         int mid = (l+r)/2;
  23.  
  24.         if(v[mid] == x){
  25.             return mid;
  26.         }
  27.         if(x > v[mid]){
  28.             l = mid+1;
  29.         }
  30.         if(x < v[mid]){
  31.             r = mid-1;
  32.         }
  33.     }
  34.  
  35.     return -1;
  36. }
  37.  
  38. /*
  39. A função binary_search(v, v+n, x) já está definida na STL e retorna true se x está contido em v ou false caso contrário.
  40.  
  41. ---Lower Bound---
  42.  
  43. No vetor  v: lower_bound(v, v+n, x);
  44. No vector v: lower_bound(v.begin(), v.end(), x);
  45.  
  46. Retorna o endereço de memória do primeiro valor >= x no vetor v. Se este valor não existir, retorna o endereço do fim do vetor.
  47.  
  48. ---Upper Bound---
  49.  
  50. No vetor  v: upper_bound(v, v+n, x);
  51. No vector v: upper_bound(v.begin(), v.end(), x);
  52.  
  53. Retorna o endereço de memória do primeiro valor > x no vetor v. Se este valor não existir, retorna o endereço do fim do vetor.
  54.  
  55. Lower e Upper devem só funcionam corretamente em um vetor ordenado.
  56.  
  57. Para contar o número de ocorrência de x da seguinte forma:
  58.  
  59. int freq = upper_bound(v, v+n, x) - lower_bound(v, v+n, x);
  60. */
  61.  
  62. int main(){
  63.  
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement