#include <iostream>
using namespace std;
// Meta Binary Search function
int metaBinarySearch(int arr[], int n, int x) {
int low = 0, high = n - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == x)
return mid;
// If the element is in the first half
if (x < arr[mid])
high = mid - 1;
// If the element is in the second half
else
low = mid + 1;
}
// If the element is not present in the array
return -1;
}
int main() {
int arr[] = {2, 3, 4, 10, 40};
int n = sizeof(arr) / sizeof(arr[0]);
int x = 10;
int result = metaBinarySearch(arr, n, x);
if (result == -1)
cout << "Element not present in the array";
else
cout << "Element found at index " << result;
return 0;
}
No comments:
Post a Comment
Fell free to write your query in comment. Your Comments will be fully encouraged.