Skip to content

Commit 020904d

Browse files
authored
Create MetaBinarySearch.java
1 parent a163816 commit 020904d

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

MetaBinarySearch.java

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import java.util.Scanner;
2+
3+
public class MetaBinarySearch {
4+
public static int metaBinarySearch(int[] arr, int target) {
5+
int left = 0, right = arr.length;
6+
7+
while (left < right) {
8+
int mid = left + (right - left) / 2;
9+
if (arr[mid] < target)
10+
{
11+
left = mid + 1;
12+
} else right = mid;
13+
}
14+
if (left == arr.length) return -1;
15+
return arr[left];
16+
}
17+
18+
public static void main(String[] args) {
19+
Scanner sc = new Scanner(System.in);
20+
System.out.print("Enter number of elements: ");
21+
int n = sc.nextInt();
22+
int[] arr = new int[n];
23+
24+
System.out.println("Enter the sorted elements:");
25+
for (int i = 0; i < n; i++) {
26+
arr[i] = sc.nextInt();
27+
}
28+
System.out.print("Enter the target value: ");
29+
int target = sc.nextInt();
30+
int result = metaBinarySearch(arr, target);
31+
if (result == -1) {
32+
System.out.println("No element found that is greater than or equal to " + target);
33+
} else {
34+
System.out.println("The smallest element >= " + target + " is " + result);
35+
}
36+
}
37+
}

0 commit comments

Comments
 (0)