Advertisement
HabKaffee

Untitled

Jul 8th, 2021
624
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <ctime>
  5. #include <cstdlib>
  6. #include <algorithm>
  7.  
  8. void printVector(std::vector<int>& vect) {
  9.     for (auto obj : vect) {
  10.         std::cout << obj << "\t";
  11.     }
  12.     std::cout << std::endl;
  13. }
  14.  
  15. int cmp (int a, int b) { return a < b ? true : false; }
  16.  
  17. int binarySearch(std::vector<int>& vector, int key, int lBorder, int rBorder) {
  18.     if (rBorder - lBorder >= 0) {
  19.         int middle = (lBorder + rBorder) / 2;
  20.         if (key == vector[middle]) {
  21.             return middle;
  22.         } else if (key < vector[middle]) {
  23.             binarySearch(vector, key, lBorder, middle - 1);
  24.         } else {
  25.             binarySearch(vector, key, middle + 1, rBorder);
  26.         }
  27.     } else {
  28.         return -1;
  29.     }
  30. }
  31.  
  32. int main() {
  33.     srand(time(NULL));
  34.     std::vector<int> objVector;
  35.     for (size_t i = 0; i < 10; ++i) {
  36.         objVector.push_back(std::rand()%100);
  37.     }
  38.     printVector(objVector);
  39.     std::sort(objVector.begin(), objVector.end(), cmp);
  40.     printVector(objVector);
  41.     int key = INT_MIN;
  42.     std::cin >> key;
  43.     int index = binarySearch(objVector, key, 0, objVector.size());
  44.     std::cout << "Index of founded element (if it isn't exist you'll see -1)\t" << index << std::endl;
  45.     return 0;
  46. }
  47.  
Advertisement
RAW Paste Data Copied
Advertisement