1+ package com .thealgorithms .searches ;
2+
3+ /**
4+ * Binary Search implementation specifically for String arrays
5+ * This algorithm finds the position of a target string within a sorted string array
6+ *
7+ * Time Complexity: O(log n * m) where n is array length and m is average string length
8+ * Space Complexity: O(1)
9+ *
10+ * @author Jeevan Yewale (https://github.com/JeevanYewale)
11+ */
12+ public final class BinarySearchStrings {
13+
14+ private BinarySearchStrings () {
15+ // Utility class
16+ }
17+
18+ /**
19+ * Performs binary search on a sorted string array
20+ *
21+ * @param array sorted array of strings (must be sorted in lexicographical order)
22+ * @param target the string to search for
23+ * @return index of target string if found, -1 otherwise
24+ */
25+ public static int search (String [] array , String target ) {
26+ if (array == null || array .length == 0 || target == null ) {
27+ return -1 ;
28+ }
29+
30+ int left = 0 ;
31+ int right = array .length - 1 ;
32+
33+ while (left <= right ) {
34+ int mid = left + (right - left ) / 2 ;
35+ int comparison = target .compareTo (array [mid ]);
36+
37+ if (comparison == 0 ) {
38+ return mid ; // Found the target
39+ } else if (comparison < 0 ) {
40+ right = mid - 1 ; // Target is in left half
41+ } else {
42+ left = mid + 1 ; // Target is in right half
43+ }
44+ }
45+
46+ return -1 ; // Target not found
47+ }
48+
49+ /**
50+ * Performs case-insensitive binary search on a sorted string array
51+ *
52+ * @param array sorted array of strings (must be sorted in lexicographical order, case-insensitive)
53+ * @param target the string to search for
54+ * @return index of target string if found, -1 otherwise
55+ */
56+ public static int searchIgnoreCase (String [] array , String target ) {
57+ if (array == null || array .length == 0 || target == null ) {
58+ return -1 ;
59+ }
60+
61+ int left = 0 ;
62+ int right = array .length - 1 ;
63+ String targetLower = target .toLowerCase ();
64+
65+ while (left <= right ) {
66+ int mid = left + (right - left ) / 2 ;
67+ int comparison = targetLower .compareTo (array [mid ].toLowerCase ());
68+
69+ if (comparison == 0 ) {
70+ return mid ; // Found the target
71+ } else if (comparison < 0 ) {
72+ right = mid - 1 ; // Target is in left half
73+ } else {
74+ left = mid + 1 ; // Target is in right half
75+ }
76+ }
77+
78+ return -1 ; // Target not found
79+ }
80+ }
0 commit comments