From 390dd43655efc0f968ac84cba74c7bdbf900a5f1 Mon Sep 17 00:00:00 2001 From: Pranjali86 Date: Thu, 7 May 2026 18:59:53 +0530 Subject: [PATCH 1/2] Add: SentinelBinarySearch algorithm with tests --- .../searches/SentinelBinarySearch.java | 44 +++++++++++++++++++ .../searches/SentinelBinarySearchTest.java | 38 ++++++++++++++++ 2 files changed, 82 insertions(+) create mode 100644 src/main/java/com/thealgorithms/searches/SentinelBinarySearch.java create mode 100644 src/test/java/com/thealgorithms/searches/SentinelBinarySearchTest.java 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..e73d296d88bf --- /dev/null +++ b/src/main/java/com/thealgorithms/searches/SentinelBinarySearch.java @@ -0,0 +1,44 @@ +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(logn) +* Best case: O(1) +*/ +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 Date: Thu, 7 May 2026 19:12:36 +0530 Subject: [PATCH 2/2] Add: Wikipedia reference link to SentinelBinarySearch --- .../java/com/thealgorithms/searches/SentinelBinarySearch.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/main/java/com/thealgorithms/searches/SentinelBinarySearch.java b/src/main/java/com/thealgorithms/searches/SentinelBinarySearch.java index e73d296d88bf..c89934475cad 100644 --- a/src/main/java/com/thealgorithms/searches/SentinelBinarySearch.java +++ b/src/main/java/com/thealgorithms/searches/SentinelBinarySearch.java @@ -10,6 +10,8 @@ * * Worst case: O(logn) * Best case: O(1) +* +* Wiki */ public class SentinelBinarySearch { /**