xxxxxxxxxx
// 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;
}
xxxxxxxxxx
#include <vector>
using namespace std;
int binarySearch(vector<int> v, int x) {
int l = 0, r = v.size() - 1, mid = 0;
while (l <= r) {
mid = l + (r - l) / 2;
if (v[mid] == x) return mid;
else if (v[mid] > x) {
r = mid - 1;
}
else{
l = mid + 1;
}
}
return -1;
}
xxxxxxxxxx
#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;
}
xxxxxxxxxx
int binarySearch(arr, low, high, key) {
if (high >= low) {
int mid = low + (high - low) / 2;
if (arr[mid] == key) return mid;
else if (arr[mid] > key) return binarySearch(arr, low, mid - 1, key);
else return binarySearch(arr, mid + 1, high, key);
}
return -1;
}
xxxxxxxxxx
// 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);
}
xxxxxxxxxx
int binarySearch(int arr[], int l, int r, int x)
{
if (r >= l) {
int mid = l + (r - l) / 2;
if (arr[mid] == x)
return mid;
if (arr[mid] > x)
return binarySearch(arr, l, mid - 1, x);
return binarySearch(arr, mid + 1, r, x);
}
return -1;
}
xxxxxxxxxx
#include <iostream>
using namespace std;
int binarySearch(int arr[], int left, int right, int target) {
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; // Element not found
}
int main() {
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 5;
int result = binarySearch(arr, 0, n - 1, target);
if (result != -1) {
cout << "Element found at index " << result << endl;
} else {
cout << "Element not found in the array" << endl;
}
return 0;
}