forked from Pranav-173/DSA
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathUniform_binarysearch.java
More file actions
62 lines (58 loc) · 2.02 KB
/
Uniform_binarysearch.java
File metadata and controls
62 lines (58 loc) · 2.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import java.util.Scanner;
import java.util.Arrays;
public class Uniform_binarysearch {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the length of the Array: ");
int size = sc.nextInt();
System.out.println("Enter Array elements in non-decreasing (sorted) order: ");
int arr[] = new int[size];
for (int i = 0; i < size; i++) {
arr[i] = sc.nextInt();
}
System.out.println("Entered Array: " + Arrays.toString(arr));
if (!isSorted(arr)) {
System.out.println("Invalid input: Uniform Binary Search requires a sorted array in non-decreasing order.");
sc.close();
return;
}
System.out.println("Enter the key element to be Found: ");
int key = sc.nextInt();
int result = binunisearch(arr, key);
if (result != -1) {
System.out.println("Element " + key + " Found at Index: " + result);
} else {
System.out.println("Element " + key + " was NOT Found in the entered Array.");
}
sc.close();
}
public static int binunisearch(int[] arr, int key) {
int n = arr.length;
int k = (int)(Math.log(n) / Math.log(2));
System.out.println("n = " + n);
System.out.println("k = " + k);
int[] offset = new int[k + 1];
offset[0] = 1 << k;
for (int i = 1; i <= k; i++) {
offset[i] = offset[i-1] / 2;
}
int index = -1;
for (int i = 0; i <= k; i++) {
int next = index + offset[i];
if (next < n && arr[next] <= key) {
index = next;
}
}
if (index >= 0 && arr[index] == key)
return index;
return -1;
}
public static boolean isSorted(int[] arr) {
for (int i = 1; i < arr.length; i++) {
if (arr[i] < arr[i - 1]) {
return false;
}
}
return true;
}
}