Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 53 additions & 16 deletions Searching-algorithms/Uniform_binarysearch.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ public static void main(String[] args) {
}
if (size == 0) {
System.out.println("Nothing to sort/search");
runDeterministicDemo();
sc.close();
return;
}
Expand All @@ -31,6 +32,7 @@ public static void main(String[] args) {

if (!isSorted(arr)) {
System.out.println("Invalid input: Uniform Binary Search requires a sorted array in non-decreasing order.");
runDeterministicDemo();
sc.close();
return;
}
Expand All @@ -43,33 +45,68 @@ public static void main(String[] args) {
} else {
System.out.println("Element " + key + " was NOT Found in the entered Array.");
}

runDeterministicDemo();
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;
}
int[] deltas = buildDeltaTable(n);
int probe = deltas[0] - 1; // center probe
probe = Math.max(0, Math.min(n - 1, probe));

for (int i = 0; i < deltas.length; i++) {
if (arr[probe] == key) {
return probe;
}

if (i == deltas.length - 1) {
break;
}

int move = deltas[i + 1];
if (key < arr[probe]) {
probe -= move;
} else {
probe += move;
}

// Keep the probe index within valid bounds.
probe = Math.max(0, Math.min(n - 1, probe));
}
if (index >= 0 && arr[index] == key)
return index;

return -1;
}

private static int[] buildDeltaTable(int n) {
int[] temp = new int[32];
int count = 0;
int delta = (n + 1) / 2;

while (delta > 0) {
temp[count++] = delta;
delta /= 2;
}

return Arrays.copyOf(temp, count);
}

private static void runDeterministicDemo() {
int[] demoArr = {2, 5, 8, 12, 16, 23, 38, 56, 72, 91};
int foundKey = 23;
int notFoundKey = 24;

System.out.println("\nDeterministic UBS demonstration");
System.out.println("Demo array: " + Arrays.toString(demoArr));
System.out.println("Search key (found case) " + foundKey + " -> index: " + binunisearch(demoArr, foundKey));
System.out.println("Search key (not-found case) " + notFoundKey + " -> index: " + binunisearch(demoArr, notFoundKey));
}

public static boolean isSorted(int[] arr) {
if (arr == null || arr.length < 2) {
return true;
Expand Down
Loading