// Recherche binaire dans un tableau trié. Version itérative. #include #include #include using namespace std; // An iterative binary search function. int binarySearch(const vector &arr, int low, int high, const int x) { while(low <= high) { int mid = low + (high - low) / 2; // Check if x is present at mid if(arr[mid] == x) return mid; else if(arr[mid] < x) // If x greater, ignore left half low = mid + 1; else // If x is smaller, ignore right half high = mid - 1; } // If we reach here, then element was not present return -1; } // binarySearch() int main(void) { int n = 0; cin >> n; // nombre de valeurs à lire vector liste(n); for(int k = 0; k < n; k++) cin >> liste[k]; sort(liste.begin(), liste.end()); for(auto x : liste) cout << x << ' '; cout << '\n'; int m = 0; cin >> m; // nombre de valeurs à chercher for(int k = 0; k < m; k++) { int val = 0; cin >> val; cout << "Valeur " << val << ' '; int indice = binarySearch(liste, 0, n - 1, val); if(indice == -1) cout << "absente\n"; else cout << "à l'indice " << indice << '\n'; } return 0; } // main()