Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- using namespace std;
- int binarySearch(vector<int>& arr, int target) {
- int left = 0;
- int right = arr.size() - 1;
- while (right - left > 1) {
- int mid = left + (right - left) / 2;
- if (arr[mid] == target) {
- return mid;
- } else if (arr[mid] < target) {
- left = mid;
- } else {
- right = mid;
- }
- }
- if (arr[left] == target) {
- return left;
- } else if (arr[right] == target) {
- return right;
- } else {
- return -1; // Элемент не найден
- }
- }
- int main() {
- vector<int> arr = {1, 3, 5, 7, 9, 11, 13};
- int target = 7;
- int result = binarySearch(arr, target);
- if (result != -1) {
- cout << "Элемент найден в позиции: " << result << endl;
- } else {
- cout << "Элемент не найден." << endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement