|
| 1 | +package com.thealgorithms.searches; |
| 2 | + |
| 3 | +import static org.junit.jupiter.api.Assertions.assertEquals; |
| 4 | + |
| 5 | +import org.junit.jupiter.api.Test; |
| 6 | + |
| 7 | +class TernarySearchTest { |
| 8 | + |
| 9 | + @Test |
| 10 | + void testFindElementInSortedArray() { |
| 11 | + Integer[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; |
| 12 | + TernarySearch search = new TernarySearch(); |
| 13 | + |
| 14 | + int index = search.find(arr, 5); |
| 15 | + |
| 16 | + assertEquals(4, index, "Should find the element 5 at index 4"); |
| 17 | + } |
| 18 | + |
| 19 | + @Test |
| 20 | + void testElementNotFound() { |
| 21 | + Integer[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; |
| 22 | + TernarySearch search = new TernarySearch(); |
| 23 | + |
| 24 | + int index = search.find(arr, 11); |
| 25 | + |
| 26 | + assertEquals(-1, index, "Should return -1 for element 11 which is not present"); |
| 27 | + } |
| 28 | + |
| 29 | + @Test |
| 30 | + void testFindFirstElement() { |
| 31 | + Integer[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; |
| 32 | + TernarySearch search = new TernarySearch(); |
| 33 | + |
| 34 | + int index = search.find(arr, 1); |
| 35 | + |
| 36 | + assertEquals(0, index, "Should find the first element 1 at index 0"); |
| 37 | + } |
| 38 | + |
| 39 | + @Test |
| 40 | + void testFindLastElement() { |
| 41 | + Integer[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; |
| 42 | + TernarySearch search = new TernarySearch(); |
| 43 | + |
| 44 | + int index = search.find(arr, 10); |
| 45 | + |
| 46 | + assertEquals(9, index, "Should find the last element 10 at index 9"); |
| 47 | + } |
| 48 | + |
| 49 | + @Test |
| 50 | + void testFindInLargeArray() { |
| 51 | + Integer[] arr = new Integer[1000]; |
| 52 | + for (int i = 0; i < 1000; i++) { |
| 53 | + arr[i] = i + 1; // Array from 1 to 1000 |
| 54 | + } |
| 55 | + TernarySearch search = new TernarySearch(); |
| 56 | + |
| 57 | + int index = search.find(arr, 500); |
| 58 | + |
| 59 | + assertEquals(499, index, "Should find element 500 at index 499"); |
| 60 | + } |
| 61 | + |
| 62 | + @Test |
| 63 | + void testNegativeNumbers() { |
| 64 | + Integer[] arr = {-10, -5, -3, -1, 0, 1, 3, 5, 7, 10}; |
| 65 | + TernarySearch search = new TernarySearch(); |
| 66 | + |
| 67 | + int index = search.find(arr, -3); |
| 68 | + |
| 69 | + assertEquals(2, index, "Should find the element -3 at index 2"); |
| 70 | + } |
| 71 | + |
| 72 | + @Test |
| 73 | + void testEdgeCaseEmptyArray() { |
| 74 | + Integer[] arr = {}; |
| 75 | + TernarySearch search = new TernarySearch(); |
| 76 | + |
| 77 | + int index = search.find(arr, 5); |
| 78 | + |
| 79 | + assertEquals(-1, index, "Should return -1 for an empty array"); |
| 80 | + } |
| 81 | +} |
0 commit comments