|
| 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, target) => { |
| 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 = 0 |
| 34 | + while (array[index] !== target) index++ |
| 35 | + |
| 36 | + // Put the last element back |
| 37 | + array[arrayLength - 1] = last |
| 38 | + |
| 39 | + if (index < arrayLength - 1 || array[arrayLength - 1] === target) return index |
| 40 | + return null |
| 41 | +} |
0 commit comments