Repository: TheAlgorithms/Java
Pull request #5664 (2024-10-09 06:14:46)

Add tests, remove `main`, improve docs in `ExponentialSearch`
<!--
Thank you for your contribution!
In order to reduce the number of notifications sent to the maintainers, please:
- create your PR as draft, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/about-pull-requests#draft-pull-requests,
- make sure that all of the CI checks pass,
- mark your PR as ready for review, cf. https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/changing-the-stage-of-a-pull-request#marking-a-pull-request-as-ready-for-review
-->

<!-- For completed items, change [ ] to [x] -->

- [x] I have read [CONTRIBUTING.md](https://github.com/TheAlgorithms/Java/blob/master/CONTRIBUTING.md).
- [x] This pull request is all my own work -- I have not plagiarized it.
- [x] All filenames are in PascalCase.
- [x] All functions and variable names follow Java naming conventions.
- [x] All new algorithms have a URL in their comments that points to Wikipedia or other similar explanations.
- [x] All new code is formatted with `clang-format -i --style=file path/to/your/file.java`

codecov-commenter: ## [Codecov](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5664?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) Report
Attention: Patch coverage is `83.33333%` with `1 line` in your changes missing coverage. Please review.
> Project coverage is 58.92%. Comparing base [(`b54cc21`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/b54cc21ade112e20f429964dc86f8543a5605d98?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) to head [(`c6c618a`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/c6c618a34c2ccaa339f57c6287acb9a5237b808d?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).
> Report is 2 commits behind head on master.

| [Files with missing lines](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5664?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) | Patch % | Lines |
|---|---|---|
| [...a/com/thealgorithms/searches/ExponentalSearch.java](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5664?src=pr&el=tree&filepath=src%2Fmain%2Fjava%2Fcom%2Fthealgorithms%2Fsearches%2FExponentalSearch.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms#diff-c3JjL21haW4vamF2YS9jb20vdGhlYWxnb3JpdGhtcy9zZWFyY2hlcy9FeHBvbmVudGFsU2VhcmNoLmphdmE=) | 83.33% | [0 Missing and 1 partial :warning: ](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5664?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) |

<details><summary>Additional details and impacted files</summary>


```diff
@@             Coverage Diff              @@
##             master    #5664      +/-   ##
============================================
+ Coverage     58.59%   58.92%   +0.33%     
- Complexity     3749     3766      +17     
============================================
  Files           554      555       +1     
  Lines         15922    15921       -1     
  Branches       3030     3036       +6     
============================================
+ Hits           9330     9382      +52     
+ Misses         6195     6135      -60     
- Partials        397      404       +7     
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5664?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).   
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).


Patch:
diff --git a/DIRECTORY.md b/DIRECTORY.md
index 0726337c..7690d09a 100644
--- a/DIRECTORY.md
+++ b/DIRECTORY.md
@@ -1001,6 +1001,7 @@
             * [BM25InvertedIndexTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/searches/BM25InvertedIndexTest.java)
             * [BreadthFirstSearchTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/searches/BreadthFirstSearchTest.java)
             * [DepthFirstSearchTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/searches/DepthFirstSearchTest.java)
+            * [ExponentialSearchTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/searches/ExponentialSearchTest.java)
             * [FibonacciSearchTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/searches/FibonacciSearchTest.java)
             * [HowManyTimesRotatedTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/searches/HowManyTimesRotatedTest.java)
             * [KMPSearchTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/searches/KMPSearchTest.java)
diff --git a/src/main/java/com/thealgorithms/searches/ExponentalSearch.java b/src/main/java/com/thealgorithms/searches/ExponentalSearch.java
index a856bd65..9187dcbc 100644
--- a/src/main/java/com/thealgorithms/searches/ExponentalSearch.java
+++ b/src/main/java/com/thealgorithms/searches/ExponentalSearch.java
@@ -2,44 +2,47 @@ package com.thealgorithms.searches;
 
 import com.thealgorithms.devutils.searches.SearchAlgorithm;
 import java.util.Arrays;
-import java.util.Random;
-import java.util.concurrent.ThreadLocalRandom;
-import java.util.stream.IntStream;
 
+/**
+ * ExponentialSearch is an algorithm that efficiently finds the position of a target
+ * value within a sorted array. It works by expanding the range to find the bounds
+ * where the target might exist and then using binary search within that range.
+ *
+ * <p>
+ * Worst-case time complexity: O(log n)
+ * Best-case time complexity: O(1) when the element is found at the first position.
+ * Average time complexity: O(log n)
+ * Worst-case space complexity: O(1)
+ * </p>
+ *
+ * <p>
+ * Note: This algorithm requires that the input array be sorted.
+ * </p>
+ */
 class ExponentialSearch implements SearchAlgorithm {
 
-    public static void main(String[] args) {
-        Random r = ThreadLocalRandom.current();
-
-        int size = 100;
-        int maxElement = 100000;
-
-        Integer[] integers = IntStream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().boxed().toArray(Integer[] ::new);
-
-        // The element that should be found
-        int shouldBeFound = integers[r.nextInt(size - 1)];
-
-        ExponentialSearch search = new ExponentialSearch();
-        int atIndex = search.find(integers, shouldBeFound);
-
-        System.out.printf("Should be found: %d. Found %d at index %d. An array length %d%n", shouldBeFound, integers[atIndex], atIndex, size);
-
-        int toCheck = Arrays.binarySearch(integers, shouldBeFound);
-        System.out.printf("Found by system method at an index: %d. Is equal: %b%n", toCheck, toCheck == atIndex);
-    }
-
+    /**
+     * Finds the index of the specified key in a sorted array using exponential search.
+     *
+     * @param array The sorted array to search.
+     * @param key The element to search for.
+     * @param <T> The type of the elements in the array, which must be comparable.
+     * @return The index of the key if found, otherwise -1.
+     */
     @Override
     public <T extends Comparable<T>> int find(T[] array, T key) {
-        if (array[0] == key) {
+        if (array.length == 0) {
+            return -1;
+        }
+        if (array[0].equals(key)) {
             return 0;
         }
-        if (array[array.length - 1] == key) {
-            return array.length;
+        if (array[array.length - 1].equals(key)) {
+            return array.length - 1;
         }
 
         int range = 1;
-
-        while (range < array.length && array[range].compareTo(key) <= -1) {
+        while (range < array.length && array[range].compareTo(key) < 0) {
             range = range * 2;
         }
 


Test patch:
diff --git a/src/test/java/com/thealgorithms/searches/ExponentialSearchTest.java b/src/test/java/com/thealgorithms/searches/ExponentialSearchTest.java
new file mode 100644
index 00000000..c84da531
--- /dev/null
+++ b/src/test/java/com/thealgorithms/searches/ExponentialSearchTest.java
@@ -0,0 +1,84 @@
+package com.thealgorithms.searches;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import java.util.stream.IntStream;
+import org.junit.jupiter.api.Test;
+
+/**
+ * Unit tests for the ExponentialSearch class.
+ */
+class ExponentialSearchTest {
+
+    /**
+     * Test for basic exponential search functionality.
+     */
+    @Test
+    void testExponentialSearchFound() {
+        ExponentialSearch exponentialSearch = new ExponentialSearch();
+        Integer[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
+        int key = 7;
+        int expectedIndex = 6; // Index of the key in the array
+        assertEquals(expectedIndex, exponentialSearch.find(array, key), "The index of the found element should be 6.");
+    }
+
+    /**
+     * Test for exponential search with the first element as the key.
+     */
+    @Test
+    void testExponentialSearchFirstElement() {
+        ExponentialSearch exponentialSearch = new ExponentialSearch();
+        Integer[] array = {1, 2, 3, 4, 5};
+        int key = 1; // First element
+        int expectedIndex = 0; // Index of the key in the array
+        assertEquals(expectedIndex, exponentialSearch.find(array, key), "The index of the first element should be 0.");
+    }
+
+    /**
+     * Test for exponential search with the last element as the key.
+     */
+    @Test
+    void testExponentialSearchLastElement() {
+        ExponentialSearch exponentialSearch = new ExponentialSearch();
+        Integer[] array = {1, 2, 3, 4, 5};
+        int key = 5; // Last element
+        int expectedIndex = 4; // Index of the key in the array
+        assertEquals(expectedIndex, exponentialSearch.find(array, key), "The index of the last element should be 4.");
+    }
+
+    /**
+     * Test for exponential search with a single element present.
+     */
+    @Test
+    void testExponentialSearchSingleElementFound() {
+        ExponentialSearch exponentialSearch = new ExponentialSearch();
+        Integer[] array = {1};
+        int key = 1; // Only element present
+        int expectedIndex = 0; // Index of the key in the array
+        assertEquals(expectedIndex, exponentialSearch.find(array, key), "The index of the single element should be 0.");
+    }
+
+    /**
+     * Test for exponential search with an empty array.
+     */
+    @Test
+    void testExponentialSearchEmptyArray() {
+        ExponentialSearch exponentialSearch = new ExponentialSearch();
+        Integer[] array = {}; // Empty array
+        int key = 1; // Key not present
+        int expectedIndex = -1; // Key not found
+        assertEquals(expectedIndex, exponentialSearch.find(array, key), "The element should not be found in an empty array.");
+    }
+
+    /**
+     * Test for exponential search on large array.
+     */
+    @Test
+    void testExponentialSearchLargeArray() {
+        ExponentialSearch exponentialSearch = new ExponentialSearch();
+        Integer[] array = IntStream.range(0, 10000).boxed().toArray(Integer[] ::new); // Array from 0 to 9999
+        int key = 9999;
+        int expectedIndex = 9999;
+        assertEquals(expectedIndex, exponentialSearch.find(array, key), "The index of the last element should be 9999.");
+    }
+}