Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- int busquedaBinaria(const vector <int> &v, int valor)
- {
- int ini = 0;
- int fin = v.size()-1;
- while(ini+1 < fin) ///ini = 5 y fin = 6, termina (es un ejemplo)
- {
- int mid = (ini+fin)/2;
- if(v[mid] < valor)
- {
- ini = mid;
- }
- else if(valor < v[mid])
- {
- fin = mid;
- }
- else
- {
- ///valor es igual a v[mid]
- return mid;
- }
- }
- if(v[ini] == valor)
- {
- return ini;
- }
- if(v[fin] == valor)
- {
- return fin;
- }
- return -1;
- }
- /**
- 16
- 12 6 11 9 5 3 0 1 87 2 40 35 27 64 22 33
- 5
- 9 40 36 -1 0
- **/
- int main()
- {
- int n;
- cin >> n;
- vector <int> v(n);
- for(int i=0; i<n; i++)
- {
- cin >> v[i];
- }
- sort(v.begin(), v.end());
- cout << "Ordenado: " << endl;
- for(int i=0; i<n; i++)
- {
- cout << v[i] << " ";
- }
- cout << endl;
- int q;
- cin >> q;
- for(int i=0; i<q; i++)
- {
- int valor;
- cin >> valor;
- ///int resultado = binary_search(v.begin(), v.end(), valor);
- vector<int>::iterator it = lower_bound(v.begin(), v.end(), valor);
- /**
- El número mas chico que sea igual o mayor a valor
- **/
- if(it == v.end())
- {
- cout << valor << " No existe" << endl;
- }
- else
- {
- if(*it == valor)
- {
- cout << valor << " Encontrado en la posicion " << it-v.begin() << endl;// en la posicion " << resultado << endl;
- }
- else
- {
- cout << valor << " no encontrado, pero devolvio " << *it << endl;
- }
- }
- }
- return 0;
- }
Add Comment
Please, Sign In to add comment