Skip to content

Commit 6fc7f3f

Browse files
authored
feat: Added Sentinel Search (TheAlgorithms#163)
* feat: added Sentinel Search * return type to null if element not found
1 parent d8fc33a commit 6fc7f3f

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

search/sentinel_search.ts

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* @function sentinelSearch
3+
* @description Sentinel search algorithm for array.
4+
*
5+
* Sentinel linear search is a variation of the standard linear search algorithm used to
6+
* find a target value in an array or list. The basic idea behind this algorithm is to add a
7+
* sentinel value at the end of the array which is equal to the target value we are looking for.
8+
* This helps to avoid checking the array boundary condition during each iteration of the loop,
9+
* as the sentinel value acts as a stopper for the loop.
10+
*
11+
* @param {number[]} array - sorted list of numbers
12+
* @param {number} target - target number to search for
13+
* @return {number|null} - index of the target number in the list, or null if not found
14+
* @see [SentinelSearch](https://www.geeksforgeeks.org/sentinel-linear-search/)
15+
* @example sentinelSearch([1,2,3], 2) => 1
16+
* @example sentinelSearch([4,5,6], 2) => null
17+
* @complexity_analysis
18+
* Time Complexity :
19+
* Worst Case -> The time complexity of the Sentinel Linear Search algorithm is O(n) in the worst case.
20+
* Best Case -> In the best case, when the key is found in the first iteration, the time complexity will be O(1).
21+
* Average Case -> However, the average time complexity is still O(n).
22+
* Auxiliary Space: O(1)
23+
*/
24+
25+
export const sentinelSearch = (array: number[], target: number): number|null => {
26+
const arrayLength = array.length
27+
if (arrayLength === 0) return null;
28+
29+
// Element to be searched is placed at the last index
30+
const last = array[arrayLength-1]
31+
array[arrayLength-1] = target
32+
33+
let index: number = 0
34+
while (array[index] !== target) index += 1
35+
36+
// Put the last element back
37+
array[arrayLength-1] = last
38+
39+
if ((index < arrayLength - 1) || (array[arrayLength - 1] === target))
40+
return index
41+
return null
42+
}

search/test/sentinel_search.test.ts

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import { sentinelSearch } from "../sentinel_search";
2+
3+
describe("Sentinel search", () => {
4+
test.each([
5+
[['o', 'b', 'c'], 'c', 2],
6+
[[1, 2, 3, 4, 5], 4, 3],
7+
[['s', 't', 'r', 'i', 'n', 'g'], 'a', null],
8+
[['1','2','3'],'1',0],
9+
[['4','e','6','10'],4,null]
10+
])(
11+
"of %o , searching for %o, expected %i",
12+
(array: any[], target: any, index: number|null) => {
13+
expect(sentinelSearch(array, target)).toStrictEqual(index)
14+
},
15+
);
16+
});

0 commit comments

Comments
 (0)