Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <random>
- #include <algorithm>
- template<typename T>
- static const T *binary_search(const T *begin, const T *end, T value)
- {
- if(begin > --end)
- return nullptr;
- do {
- const T *const mid = begin + (size_t(end - begin) >> 1u);
- if(*mid < value)
- begin = mid + 1;
- else
- end = mid;
- } while(begin < end);
- return *begin == value ? begin : nullptr;
- }
- template<typename T, size_t N>
- inline const T *binary_search(const T (&data)[N], T value)
- { return binary_search(data, data + N, value); }
- int main()
- {
- using Type = uint64_t;
- static constexpr size_t Count = 32;
- Type data[Count];
- std::random_device rd;
- std::mt19937 rnd(rd());
- std::uniform_int_distribution<Type> dist;
- for(auto &entry : data)
- entry = dist(rnd);
- std::sort(data, data + Count);
- std::cout << "Searching in {\n";
- for(const auto &entry : data)
- std::cout << " " << entry << "\n";
- std::cout << "}\n\nEnter value to search for: ";
- Type value;
- std::cin >> value;
- const auto result = binary_search(data, value);
- std::cout << "Value " << value << " is ";
- if(result)
- std::cout << "at " << (result - data) << ".\n";
- else
- std::cout << "not found.\n";
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement