Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- int binarySearch(int arr[], int size, int target) {
- int left = 0;
- int right = size - 1;
- while (left<=right) {int mid = left + (right-left)/2;
- if (arr[mid] == target) {return mid;
- }
- if (arr[mid]<target) {
- left = mid + 1;
- }
- else {right=mid-1;}
- }
- return -1;
- }
- int main() {int arr[] = {2,5,8,12,16,23,38,45,56,67,78,85,89,95,100};
- int n=15;
- int target;
- cout <<"Bъведете число за търсене:";
- cin >> target;
- int result = binarySearch(arr,n,target);
- if (result != -1){
- cout<<"Element is at index "<< result<< endl;}
- else {cout<<"Element not found "<< endl; }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment