Dimitar23308

binary search

Jan 8th, 2026
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.86 KB | None | 0 0
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int binarySearch(int arr[], int size, int target) {
  5.  
  6.     int left = 0;
  7.     int right = size - 1;
  8.  
  9.     while (left<=right) {int mid = left + (right-left)/2;
  10.    
  11.         if (arr[mid] == target) {return mid;
  12.         }
  13.  
  14.         if (arr[mid]<target) {
  15.             left = mid + 1;
  16.         }
  17.  
  18.         else {right=mid-1;}
  19.     }
  20.     return -1;
  21. }
  22.    
  23. int main() {int arr[] = {2,5,8,12,16,23,38,45,56,67,78,85,89,95,100};
  24.             int n=15;
  25.             int target;
  26.             cout <<"Bъведете число за търсене:";
  27.             cin >> target;
  28.             int result = binarySearch(arr,n,target);
  29.             if (result != -1){
  30.                 cout<<"Element is at index "<< result<< endl;}
  31.                 else {cout<<"Element not found "<< endl; }
  32.                 return 0;
  33.             }
  34.  
  35.  
  36.  
Advertisement
Add Comment
Please, Sign In to add comment