// BY shivam kumar KIIT
#include<bits/stdc++.h>
usind namespace std;
int main()
{
int arr[]={10,2,34,2,5,4,1};
sort(arr,arr+7);//sort array in ascending order before using binary search
binary_search(arr,arr+7,10);//return 1 as element is found
binary_search(arr,arr+7,3);//return 0 as element is not found
return 0;
}
#include<bits/stdc++.h>
using namespace std;
int main(){
//lets do it
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++) cin>>arr[i];
int target;
cin>>target; // target=?
int l=0,h=n-1;
int index=-1;
while(l<=h)
{
int mid=(l+h)/2;
if(arr[mid]==target){
index=mid;
break;
}else if(arr[mid]<target) l=mid+1;
else h=mid-1;
}
cout<<"NUMBER FOUND AT INDEX-"<<index<<endl;
return 0;
}
// Binary Search in C++
#include <iostream>
using namespace std;
int binarySearch(int array[], int x, int low, int high) {
// Repeat until the pointers low and high meet each other
while (low <= high) {
int mid = low + (high - low) / 2;
if (array[mid] == x)
return mid;
if (array[mid] < x)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
int main(void) {
int array[] = {3, 4, 5, 6, 7, 8, 9};
int x = 4;
int n = sizeof(array) / sizeof(array[0]);
int result = binarySearch(array, x, 0, n - 1);
if (result == -1)
printf("Not found");
else
printf("Element is found at index %d", result);
}