Advertisement
xgallom

Binary Search

May 27th, 2020
928
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.22 KB | None | 0 0
  1. #include <iostream>
  2. #include <random>
  3. #include <algorithm>
  4.  
  5. template<typename T>
  6. static const T *binary_search(const T *begin, const T *end, T value)
  7. {
  8.     if(begin > --end)
  9.         return nullptr;
  10.  
  11.     do {
  12.         const T *const mid = begin + (size_t(end - begin) >> 1u);
  13.  
  14.         if(*mid < value)
  15.             begin = mid + 1;
  16.         else
  17.             end = mid;
  18.     } while(begin < end);
  19.  
  20.     return *begin == value ? begin : nullptr;
  21. }
  22.  
  23. template<typename T, size_t N>
  24. inline const T *binary_search(const T (&data)[N], T value)
  25. { return binary_search(data, data + N, value); }
  26.  
  27. int main()
  28. {
  29.     using Type = uint64_t;
  30.     static constexpr size_t Count = 32;
  31.  
  32.     Type data[Count];
  33.  
  34.     std::random_device rd;
  35.     std::mt19937 rnd(rd());
  36.     std::uniform_int_distribution<Type> dist;
  37.  
  38.     for(auto &entry : data)
  39.         entry = dist(rnd);
  40.  
  41.     std::sort(data, data + Count);
  42.  
  43.     std::cout << "Searching in {\n";
  44.     for(const auto &entry : data)
  45.         std::cout << "  " << entry << "\n";
  46.  
  47.     std::cout << "}\n\nEnter value to search for: ";
  48.     Type value;
  49.     std::cin >> value;
  50.  
  51.     const auto result = binary_search(data, value);
  52.  
  53.     std::cout << "Value " << value << " is ";
  54.     if(result)
  55.         std::cout << "at " << (result - data) << ".\n";
  56.     else
  57.         std::cout << "not found.\n";
  58.  
  59.     return 0;
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement