Skip to content

Commit cfeefd9

Browse files
committed
UbiquitousSearch
1 parent e499d3b commit cfeefd9

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import java.util.*;
2+
3+
public class UbiquitousSearch {
4+
5+
// Method to perform Ubiquitous Search
6+
public static int ubiquitousSearch(int[] arr, int target) {
7+
int l = 0, r = arr.length - 1;
8+
9+
while (l <= r) {
10+
// Find the middle index
11+
int m = l + (r - l) / 2;
12+
13+
// Check if the middle element is the target
14+
if (arr[m] == target) {
15+
return m; // Target found
16+
}
17+
18+
// If the right half is sorted
19+
if (arr[m] < arr[r]) {
20+
// Check if the target is in the sorted right half
21+
if (arr[m] < target && target <= arr[r]) {
22+
l = m + 1;
23+
} else {
24+
r = m - 1;
25+
}
26+
}
27+
// If the left half is sorted
28+
else {
29+
// Check if the target is in the sorted left half
30+
if (arr[l] <= target && target < arr[m]) {
31+
r = m - 1;
32+
} else {
33+
l = m + 1;
34+
}
35+
}
36+
}
37+
38+
// Target not found
39+
return -1;
40+
}
41+
42+
public static void main(String[] args) {
43+
// Example usage
44+
int[] arr = {4, 5, 6, 7, 0, 1, 2};
45+
int target = 0;
46+
47+
int result = ubiquitousSearch(arr, target);
48+
if (result != -1) {
49+
System.out.println("Target found at index: " + result);
50+
} else {
51+
System.out.println("Target not found");
52+
}
53+
}
54+
}

0 commit comments

Comments
 (0)