-
Notifications
You must be signed in to change notification settings - Fork 20.9k
Add BinarySearchStrings algorithm with comprehensive tests #7221
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
JeevanYewale
wants to merge
2
commits into
TheAlgorithms:master
Choose a base branch
from
JeevanYewale:add-binary-search-improvement
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+137
−0
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
81 changes: 81 additions & 0 deletions
81
src/main/java/com/thealgorithms/searches/BinarySearchStrings.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,81 @@ | ||
| package com.thealgorithms.searches; | ||
|
|
||
| /** | ||
| * Binary Search implementation specifically for String arrays | ||
| * This algorithm finds the position of a target string within a sorted string array | ||
| * | ||
| * Time Complexity: O(log n * m) where n is array length and m is average string length | ||
| * Space Complexity: O(1) | ||
| * | ||
| * @see <a href="https://en.wikipedia.org/wiki/Binary_search_algorithm">Binary Search Algorithm</a> | ||
| * @author Jeevan Yewale (https://github.com/JeevanYewale) | ||
| */ | ||
| public final class BinarySearchStrings { | ||
|
|
||
| private BinarySearchStrings() { | ||
| // Utility class | ||
| } | ||
|
|
||
| /** | ||
| * Performs binary search on a sorted string array | ||
| * | ||
| * @param array sorted array of strings (must be sorted in lexicographical order) | ||
| * @param target the string to search for | ||
| * @return index of target string if found, -1 otherwise | ||
| */ | ||
| public static int search(String[] array, String target) { | ||
| if (array == null || array.length == 0 || target == null) { | ||
| return -1; | ||
| } | ||
|
|
||
| int left = 0; | ||
| int right = array.length - 1; | ||
|
|
||
| while (left <= right) { | ||
| int mid = left + (right - left) / 2; | ||
| int comparison = target.compareTo(array[mid]); | ||
|
|
||
| if (comparison == 0) { | ||
| return mid; // Found the target | ||
| } else if (comparison < 0) { | ||
| right = mid - 1; // Target is in left half | ||
| } else { | ||
| left = mid + 1; // Target is in right half | ||
| } | ||
| } | ||
|
|
||
| return -1; // Target not found | ||
| } | ||
|
|
||
| /** | ||
| * Performs case-insensitive binary search on a sorted string array | ||
| * | ||
| * @param array sorted array of strings (must be sorted in lexicographical order, case-insensitive) | ||
| * @param target the string to search for | ||
| * @return index of target string if found, -1 otherwise | ||
| */ | ||
| public static int searchIgnoreCase(String[] array, String target) { | ||
| if (array == null || array.length == 0 || target == null) { | ||
| return -1; | ||
| } | ||
|
|
||
| int left = 0; | ||
| int right = array.length - 1; | ||
| String targetLower = target.toLowerCase(); | ||
|
|
||
| while (left <= right) { | ||
| int mid = left + (right - left) / 2; | ||
| int comparison = targetLower.compareTo(array[mid].toLowerCase()); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. array[mid].toLowerCase() allocates a new String object every single iteration. That's heavy on memory. You should just use target.compareToIgnoreCase(array[mid]) here instead. |
||
|
|
||
| if (comparison == 0) { | ||
| return mid; // Found the target | ||
| } else if (comparison < 0) { | ||
| right = mid - 1; // Target is in left half | ||
| } else { | ||
| left = mid + 1; // Target is in right half | ||
| } | ||
| } | ||
|
|
||
| return -1; // Target not found | ||
| } | ||
| } | ||
56 changes: 56 additions & 0 deletions
56
src/test/java/com/thealgorithms/searches/BinarySearchStringsTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,56 @@ | ||
| package com.thealgorithms.searches; | ||
|
|
||
| import static org.junit.jupiter.api.Assertions.assertEquals; | ||
|
|
||
| import org.junit.jupiter.api.Test; | ||
|
|
||
| /** | ||
| * Test cases for BinarySearchStrings algorithm | ||
| * | ||
| * @author Jeevan Yewale (https://github.com/JeevanYewale) | ||
| */ | ||
| class BinarySearchStringsTest { | ||
|
|
||
| @Test | ||
| void testBasicSearch() { | ||
| String[] array = {"apple", "banana", "cherry", "date", "elderberry"}; | ||
|
|
||
| assertEquals(0, BinarySearchStrings.search(array, "apple")); | ||
| assertEquals(2, BinarySearchStrings.search(array, "cherry")); | ||
| assertEquals(4, BinarySearchStrings.search(array, "elderberry")); | ||
| assertEquals(-1, BinarySearchStrings.search(array, "grape")); | ||
| } | ||
|
|
||
| @Test | ||
| void testEmptyArray() { | ||
| String[] array = {}; | ||
| assertEquals(-1, BinarySearchStrings.search(array, "test")); | ||
| } | ||
|
|
||
| @Test | ||
| void testNullArray() { | ||
| assertEquals(-1, BinarySearchStrings.search(null, "test")); | ||
| } | ||
|
|
||
| @Test | ||
| void testNullTarget() { | ||
| String[] array = {"apple", "banana"}; | ||
| assertEquals(-1, BinarySearchStrings.search(array, null)); | ||
| } | ||
|
|
||
| @Test | ||
| void testSingleElement() { | ||
| String[] array = {"single"}; | ||
| assertEquals(0, BinarySearchStrings.search(array, "single")); | ||
| assertEquals(-1, BinarySearchStrings.search(array, "other")); | ||
| } | ||
|
|
||
| @Test | ||
| void testCaseInsensitiveSearch() { | ||
| String[] array = {"apple", "banana", "cherry", "date", "elderberry"}; | ||
|
|
||
| assertEquals(0, BinarySearchStrings.searchIgnoreCase(array, "APPLE")); | ||
| assertEquals(2, BinarySearchStrings.searchIgnoreCase(array, "Cherry")); | ||
| assertEquals(-1, BinarySearchStrings.searchIgnoreCase(array, "GRAPE")); | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The logic here is 100% identical to the search method above.
Please refactor this to use a private helper method that accepts a Comparator. That way you don't duplicate the binary search code twice.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@singhc7 Thank you for the detailed review! You're absolutely right on all points:
✅ Memory optimization: Replaced
targetLower.compareTo(array[mid].toLowerCase())withtarget.compareToIgnoreCase(array[mid])to avoid unnecessary String object creation.✅ Code deduplication: Refactored both methods to use a private
binarySearch(String[] array, String target, Comparator<String> comparator)helper method. Nowsearch()usesString::compareToandsearchIgnoreCase()usesString::compareToIgnoreCase.✅ Formatting: Will run clang-format before the next push.
The refactored code is much cleaner and more efficient. Thanks for the guidance!