GastonFontenla

Busqueda Binaria

Jul 11th, 2020
195
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.83 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. int busquedaBinaria(const vector <int> &v, int valor)
  6. {
  7.     int ini = 0;
  8.     int fin = v.size()-1;
  9.     while(ini+1 < fin) ///ini = 5 y fin = 6, termina (es un ejemplo)
  10.     {
  11.         int mid = (ini+fin)/2;
  12.         if(v[mid] < valor)
  13.         {
  14.             ini = mid;
  15.         }
  16.         else if(valor < v[mid])
  17.         {
  18.             fin = mid;
  19.         }
  20.         else
  21.         {
  22.             ///valor es igual a v[mid]
  23.             return mid;
  24.         }
  25.     }
  26.  
  27.     if(v[ini] == valor)
  28.     {
  29.         return ini;
  30.     }
  31.     if(v[fin] == valor)
  32.     {
  33.         return fin;
  34.     }
  35.  
  36.     return -1;
  37. }
  38.  
  39. /**
  40. 16
  41. 12 6 11 9 5 3 0 1 87 2 40 35 27 64 22 33
  42. 5
  43. 9 40 36 -1 0
  44. **/
  45.  
  46. int main()
  47. {
  48.     int n;
  49.     cin >> n;
  50.     vector <int> v(n);
  51.     for(int i=0; i<n; i++)
  52.     {
  53.         cin >> v[i];
  54.     }
  55.  
  56.     sort(v.begin(), v.end());
  57.  
  58.     cout << "Ordenado: " << endl;
  59.     for(int i=0; i<n; i++)
  60.     {
  61.         cout << v[i] << " ";
  62.     }
  63.     cout << endl;
  64.  
  65.     int q;
  66.     cin >> q;
  67.     for(int i=0; i<q; i++)
  68.     {
  69.         int valor;
  70.         cin >> valor;
  71.         ///int resultado = binary_search(v.begin(), v.end(), valor);
  72.         vector<int>::iterator it = lower_bound(v.begin(), v.end(), valor);
  73.         /**
  74.                 El número mas chico que sea igual o mayor a valor
  75.                 **/
  76.  
  77.         if(it == v.end())
  78.         {
  79.             cout << valor << " No existe" << endl;
  80.         }
  81.         else
  82.         {
  83.             if(*it == valor)
  84.             {
  85.                 cout << valor << " Encontrado en la posicion " << it-v.begin() << endl;// en la posicion " << resultado << endl;
  86.             }
  87.             else
  88.             {
  89.                 cout << valor << " no encontrado, pero devolvio " << *it << endl;
  90.             }
  91.         }
  92.     }
  93.  
  94.     return 0;
  95. }
Add Comment
Please, Sign In to add comment