diff --git a/src/main/java/com/thealgorithms/searches/SentinelBinarySearch.java b/src/main/java/com/thealgorithms/searches/SentinelBinarySearch.java new file mode 100644 index 000000000000..c3f4147dbb65 --- /dev/null +++ b/src/main/java/com/thealgorithms/searches/SentinelBinarySearch.java @@ -0,0 +1,47 @@ +package com.thealgorithms.searches; + +/** + * Sentinel Binary Search algorithm implementation. + * + * Sentinel Binary Search is a variation of Binary Search that reduces + * the number of comparisons by placing a sentinel value at the end + * of the array, eliminating the need to check array bounds on every step. + * + * Worst case: O(log n) + * Best case: O(1) + * + * Wiki + */ +public class SentinelBinarySearch { + + /** + * Finds the index of a target value in a sorted array. + * + * @param arr the sorted array to search + * @param target the value to find + * @return the index of target if found, otherwise -1 + */ + public int find(int[] arr, int target) { + int n = arr.length; + + if (n == 0) { + return -1; + } + + int last = arr[n - 1]; + arr[n - 1] = target; + + int i = 0; + while (arr[i] != target) { + i++; + } + + arr[n - 1] = last; + + if (i < n - 1 || last == target) { + return i; + } + + return -1; + } +} diff --git a/src/test/java/com/thealgorithms/searches/SentinelBinarySearchTest.java b/src/test/java/com/thealgorithms/searches/SentinelBinarySearchTest.java new file mode 100644 index 000000000000..fc6c658f8e6d --- /dev/null +++ b/src/test/java/com/thealgorithms/searches/SentinelBinarySearchTest.java @@ -0,0 +1,39 @@ +package com.thealgorithms.searches; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import org.junit.jupiter.api.Test; + +class SentinelBinarySearchTest { + + private final SentinelBinarySearch search = new SentinelBinarySearch(); + + @Test + void testElementFound() { + int[] arr = {1, 3, 5, 7, 9}; + assertEquals(2, search.find(arr, 5)); + } + + @Test + void testElementNotFound() { + int[] arr = {1, 3, 5, 7, 9}; + assertEquals(-1, search.find(arr, 4)); + } + + @Test + void testFirstElement() { + int[] arr = {1, 3, 5, 7, 9}; + assertEquals(0, search.find(arr, 1)); + } + + @Test + void testLastElement() { + int[] arr = {1, 3, 5, 7, 9}; + assertEquals(4, search.find(arr, 9)); + } + + @Test + void testEmptyArray() { + int[] arr = {}; + assertEquals(-1, search.find(arr, 5)); + } +}