Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
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)
*
* <a href="https://en.wikipedia.org/wiki/Linear_search#With_a_sentinel">Wiki</a>
*/
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;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package com.thealgorithms.searches;

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;

public 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));
}
}
Loading