Repository: TheAlgorithms/Java
Pull request #5668 (2024-10-09 06:44:10)

Add tests, remove main in IterativeTernarySearch
<!--
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/5668?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 `75.00000%` with `1 line` in your changes missing coverage. Please review.
> Project coverage is 59.02%. 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 [(`cf798d8`)](https://app.codecov.io/gh/TheAlgorithms/Java/commit/cf798d8ddbdf7b075d840911ebc148bd3717016a?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms).
> Report is 3 commits behind head on master.

| [Files with missing lines](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5668?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms) | Patch % | Lines |
|---|---|---|
| [...thealgorithms/searches/IterativeTernarySearch.java](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5668?src=pr&el=tree&filepath=src%2Fmain%2Fjava%2Fcom%2Fthealgorithms%2Fsearches%2FIterativeTernarySearch.java&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=TheAlgorithms#diff-c3JjL21haW4vamF2YS9jb20vdGhlYWxnb3JpdGhtcy9zZWFyY2hlcy9JdGVyYXRpdmVUZXJuYXJ5U2VhcmNoLmphdmE=) | 75.00% | [0 Missing and 1 partial :warning: ](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5668?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    #5668      +/-   ##
============================================
+ Coverage     58.59%   59.02%   +0.42%     
- Complexity     3749     3778      +29     
============================================
  Files           554      556       +2     
  Lines         15922    15944      +22     
  Branches       3030     3041      +11     
============================================
+ Hits           9330     9411      +81     
+ Misses         6195     6128      -67     
- Partials        397      405       +8     
```

</details>

[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/TheAlgorithms/Java/pull/5668?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 23f2941a..ff6e2980 100644
--- a/DIRECTORY.md
+++ b/DIRECTORY.md
@@ -1006,6 +1006,7 @@
             * [HowManyTimesRotatedTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/searches/HowManyTimesRotatedTest.java)
             * [InterpolationSearchTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/searches/InterpolationSearchTest.java)
             * [IterativeBinarySearchTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/searches/IterativeBinarySearchTest.java)
+            * [IterativeTernarySearchTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/searches/IterativeTernarySearchTest.java)
             * [KMPSearchTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/searches/KMPSearchTest.java)
             * [OrderAgnosticBinarySearchTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/searches/OrderAgnosticBinarySearchTest.java)
             * [PerfectBinarySearchTest](https://github.com/TheAlgorithms/Java/blob/master/src/test/java/com/thealgorithms/searches/PerfectBinarySearchTest.java)
diff --git a/src/main/java/com/thealgorithms/searches/IterativeTernarySearch.java b/src/main/java/com/thealgorithms/searches/IterativeTernarySearch.java
index e78acd6a..585d6787 100644
--- a/src/main/java/com/thealgorithms/searches/IterativeTernarySearch.java
+++ b/src/main/java/com/thealgorithms/searches/IterativeTernarySearch.java
@@ -1,22 +1,26 @@
 package com.thealgorithms.searches;
 
 import com.thealgorithms.devutils.searches.SearchAlgorithm;
-import java.util.Arrays;
-import java.util.Random;
-import java.util.stream.Stream;
 
 /**
- * A iterative version of a ternary search algorithm This is better way to
- * implement the ternary search, because a recursive version adds some overhead
- * to a stack. But in java the compile can transform the recursive version to
- * iterative implicitly, so there are no much differences between these two
- * algorithms
+ * An iterative implementation of the Ternary Search algorithm.
  *
  * <p>
- * Worst-case performance Θ(log3(N)) Best-case performance O(1) Average
- * performance Θ(log3(N)) Worst-case space complexity O(1)
+ * Ternary search is a divide-and-conquer algorithm that splits the array into three parts
+ * instead of two, as in binary search. This implementation is iterative, reducing the overhead
+ * associated with recursive function calls. However, the recursive version can also be optimized
+ * by the Java compiler to resemble the iterative version, resulting in similar performance.
+ *
+ * <p>
+ * Worst-case performance: Θ(log3(N))<br>
+ * Best-case performance: O(1)<br>
+ * Average performance: Θ(log3(N))<br>
+ * Worst-case space complexity: O(1)
+ *
+ * <p>
+ * This class implements the {@link SearchAlgorithm} interface, providing a generic search method
+ * for any comparable type.
  *
- * @author Podshivalov Nikita (https://github.com/nikitap492)
  * @see SearchAlgorithm
  * @see TernarySearch
  * @since 2018-04-13
@@ -25,6 +29,13 @@ public class IterativeTernarySearch implements SearchAlgorithm {
 
     @Override
     public <T extends Comparable<T>> int find(T[] array, T key) {
+        if (array == null || array.length == 0 || key == null) {
+            return -1;
+        }
+        if (array.length == 1) {
+            return array[0].compareTo(key) == 0 ? 0 : -1;
+        }
+
         int left = 0;
         int right = array.length - 1;
 
@@ -50,23 +61,4 @@ public class IterativeTernarySearch implements SearchAlgorithm {
 
         return -1;
     }
-
-    public static void main(String[] args) {
-        // just generate data
-        Random r = new Random();
-        int size = 100;
-        int maxElement = 100000;
-        Integer[] integers = Stream.generate(() -> r.nextInt(maxElement)).limit(size).sorted().toArray(Integer[] ::new);
-
-        // the element that should be found
-        Integer shouldBeFound = integers[r.nextInt(size - 1)];
-
-        IterativeTernarySearch search = new IterativeTernarySearch();
-        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);
-    }
 }


Test patch:
diff --git a/src/test/java/com/thealgorithms/searches/IterativeTernarySearchTest.java b/src/test/java/com/thealgorithms/searches/IterativeTernarySearchTest.java
new file mode 100644
index 00000000..c7640e6d
--- /dev/null
+++ b/src/test/java/com/thealgorithms/searches/IterativeTernarySearchTest.java
@@ -0,0 +1,117 @@
+package com.thealgorithms.searches;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+
+import org.junit.jupiter.api.Test;
+
+/**
+ * Unit tests for the IterativeTernarySearch class.
+ */
+class IterativeTernarySearchTest {
+
+    /**
+     * Test for basic ternary search functionality when the element is found.
+     */
+    @Test
+    void testTernarySearchFound() {
+        IterativeTernarySearch ternarySearch = new IterativeTernarySearch();
+        Integer[] array = {1, 2, 4, 8, 16, 32, 64, 128, 256, 512};
+        Integer key = 128;
+        int expectedIndex = 7; // Index of the key in the array
+        assertEquals(expectedIndex, ternarySearch.find(array, key), "The index of the found element should be 7.");
+    }
+
+    /**
+     * Test for ternary search when the element is not present in the array.
+     */
+    @Test
+    void testTernarySearchNotFound() {
+        IterativeTernarySearch ternarySearch = new IterativeTernarySearch();
+        Integer[] array = {1, 2, 4, 8, 16};
+        Integer key = 6; // Element not present in the array
+        assertEquals(-1, ternarySearch.find(array, key), "The element should not be found in the array.");
+    }
+
+    /**
+     * Test for ternary search with the first element as the key.
+     */
+    @Test
+    void testTernarySearchFirstElement() {
+        IterativeTernarySearch ternarySearch = new IterativeTernarySearch();
+        Integer[] array = {1, 2, 4, 8, 16};
+        Integer key = 1; // First element
+        assertEquals(0, ternarySearch.find(array, key), "The index of the first element should be 0.");
+    }
+
+    /**
+     * Test for ternary search with the last element as the key.
+     */
+    @Test
+    void testTernarySearchLastElement() {
+        IterativeTernarySearch ternarySearch = new IterativeTernarySearch();
+        Integer[] array = {1, 2, 4, 8, 16};
+        Integer key = 16; // Last element
+        assertEquals(4, ternarySearch.find(array, key), "The index of the last element should be 4.");
+    }
+
+    /**
+     * Test for ternary search with a single element present.
+     */
+    @Test
+    void testTernarySearchSingleElementFound() {
+        IterativeTernarySearch ternarySearch = new IterativeTernarySearch();
+        Integer[] array = {1};
+        Integer key = 1; // Only element present
+        assertEquals(0, ternarySearch.find(array, key), "The index of the single element should be 0.");
+    }
+
+    /**
+     * Test for ternary search with a single element not present.
+     */
+    @Test
+    void testTernarySearchSingleElementNotFound() {
+        IterativeTernarySearch ternarySearch = new IterativeTernarySearch();
+        Integer[] array = {1};
+        Integer key = 2; // Key not present
+        assertEquals(-1, ternarySearch.find(array, key), "The element should not be found in the array.");
+    }
+
+    /**
+     * Test for ternary search with an empty array.
+     */
+    @Test
+    void testTernarySearchEmptyArray() {
+        IterativeTernarySearch ternarySearch = new IterativeTernarySearch();
+        Integer[] array = {}; // Empty array
+        Integer key = 1; // Key not present
+        assertEquals(-1, ternarySearch.find(array, key), "The element should not be found in an empty array.");
+    }
+
+    /**
+     * Test for ternary search on a large array.
+     */
+    @Test
+    void testTernarySearchLargeArray() {
+        IterativeTernarySearch ternarySearch = new IterativeTernarySearch();
+        Integer[] array = new Integer[10000];
+        for (int i = 0; i < array.length; i++) {
+            array[i] = i * 2;
+        } // Array from 0 to 19998, step 2
+        Integer key = 9998; // Present in the array
+        assertEquals(4999, ternarySearch.find(array, key), "The index of the found element should be 4999.");
+    }
+
+    /**
+     * Test for ternary search on large array with a non-existent key.
+     */
+    @Test
+    void testTernarySearchLargeArrayNotFound() {
+        IterativeTernarySearch ternarySearch = new IterativeTernarySearch();
+        Integer[] array = new Integer[10000];
+        for (int i = 0; i < array.length; i++) {
+            array[i] = i * 2;
+        } // Array from 0 to 19998, step 2
+        Integer key = 9999; // Key not present
+        assertEquals(-1, ternarySearch.find(array, key), "The element should not be found in the array.");
+    }
+}