Advertisement
Zuneve

binary_search

Feb 25th, 2024
29
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.95 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3.  
  4. using namespace std;
  5.  
  6. int binarySearch(vector<int>& arr, int target) {
  7. int left = 0;
  8. int right = arr.size() - 1;
  9.  
  10. while (right - left > 1) {
  11. int mid = left + (right - left) / 2;
  12.  
  13. if (arr[mid] == target) {
  14. return mid;
  15. } else if (arr[mid] < target) {
  16. left = mid;
  17. } else {
  18. right = mid;
  19. }
  20. }
  21.  
  22. if (arr[left] == target) {
  23. return left;
  24. } else if (arr[right] == target) {
  25. return right;
  26. } else {
  27. return -1; // Элемент не найден
  28. }
  29. }
  30.  
  31. int main() {
  32. vector<int> arr = {1, 3, 5, 7, 9, 11, 13};
  33. int target = 7;
  34. int result = binarySearch(arr, target);
  35. if (result != -1) {
  36. cout << "Элемент найден в позиции: " << result << endl;
  37. } else {
  38. cout << "Элемент не найден." << endl;
  39. }
  40. return 0;
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement