11package com .thealgorithms .searches ;
22
33/**
4- * Sentinel Binary Search algorithm implementation
5- *
6- * Sentinel Binary Search is a variation of Binary Search that
7- * reduces the number of comparisons by placing a sentinel value
8- * at the end of the array, eliminating the need to check array
9- * bounds on every step.
10- *
11- * Worst case: O(logn)
12- * Best case: O(1)
13- *
14- * <a href="https://en.wikipedia.org/wiki/Linear_search#With_a_sentinel">Wiki</a>
15- */
4+ * Sentinel Binary Search algorithm implementation.
5+ *
6+ * Sentinel Binary Search is a variation of Binary Search that reduces
7+ * the number of comparisons by placing a sentinel value at the end
8+ * of the array, eliminating the need to check array bounds on every step.
9+ *
10+ * Worst case: O(log n)
11+ * Best case: O(1)
12+ *
13+ * <a href="https://en.wikipedia.org/wiki/Linear_search#With_a_sentinel">Wiki</a>
14+ */
1615public class SentinelBinarySearch {
16+
1717 /**
1818 * Finds the index of a target value in a sorted array.
19- *
19+ *
2020 * @param arr the sorted array to search
21- * @param target the value to find
21+ * @param target the value to find
2222 * @return the index of target if found, otherwise -1
2323 */
24- public int find (int [] arr , int target ){
24+ public int find (int [] arr , int target ) {
2525 int n = arr .length ;
2626
27- if (n == 0 ){
27+ if (n == 0 ) {
2828 return -1 ;
2929 }
3030
31- int last = arr [n - 1 ];
32- arr [n - 1 ] = target ;
31+ int last = arr [n - 1 ];
32+ arr [n - 1 ] = target ;
3333
3434 int i = 0 ;
35- while (arr [i ] != target ){
35+ while (arr [i ] != target ) {
3636 i ++;
3737 }
3838
39- arr [n - 1 ] = last ;
39+ arr [n - 1 ] = last ;
4040
41- if (i < n - 1 || last == target ){
41+ if (i < n - 1 || last == target ) {
4242 return i ;
4343 }
44+
4445 return -1 ;
4546 }
46- }
47+ }
0 commit comments