Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <algorithm>
- #include <iostream>
- #include <cstdlib>
- #include <vector>
- #include <ctime>
- using namespace std;
- int bs(const vector<int> &arr, int size, int x) {
- int low = 0, high = size - 1, mid;
- while (high >= low) {
- mid = low + (high - low) / 2;
- if (arr[mid] == x) {
- return mid;
- } else if (arr[mid] > x) {
- high = mid - 1;
- } else {
- low = mid + 1;
- }
- }
- return -1;
- }
- int main() {
- srand(time(nullptr));
- vector<int> arr(20);
- for (int i = 0; i < 20; ++i) {
- arr[i] = rand() % 100 + 1;
- }
- sort(begin(arr), end(arr));
- for (int i = 0; i < 20; ++i) {
- cout << arr[i] << " ";
- }
- cout << endl;
- cout << bs(arr, 20, 50);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement