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
84 lines (80 loc) · 2.64 KB
/
Uniform_binarysearch.java
File metadata and controls
84 lines (80 loc) · 2.64 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import java.util.Scanner;
import java.util.Arrays;
public class Uniform_binarysearch {
/*
* Edge-case behavior:
* - Negative size is rejected.
* - Size 0 exits early with "Nothing to sort/search".
* - Null/empty arrays return not found (-1).
*/
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();
if (size < 0) {
System.out.println("Invalid input: size cannot be negative.");
sc.close();
return;
}
if (size == 0) {
System.out.println("Nothing to sort/search");
sc.close();
return;
}
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) {
if (arr == null || arr.length == 0) {
return -1;
}
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) {
if (arr == null || arr.length < 2) {
return true;
}
for (int i = 1; i < arr.length; i++) {
if (arr[i] < arr[i - 1]) {
return false;
}
}
return true;
}
}