This commit is contained in:
Rohith K 2024-07-17 10:38:32 +09:00 committed by GitHub
commit 088a8a3a57
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 60 additions and 0 deletions

View File

@ -0,0 +1,9 @@
# Sentinal Linear Search
The idea in Sentinal Linear Search is to reduce the number of comparisons required to find an element in a list. Here we replace the last element of the list with the search element itself and run a while loop to see if there exists any copy of the search element in the list and quit the loop as soon as we find the search element.
## Complexity
**Time Complexity**: `O(n)` - since we're checking each element in the array
##Reference
- [Wikipedia] (https://en.wikipedia.org/wiki/Linear_search)

View File

@ -0,0 +1,19 @@
import sentinalLinearSearch from '../sentinalLinearSearch';
describe('sentinalLinearSearch', () => {
it('should search all numbers in array', () => {
const array = [1, 2, 4, 6, 2, 1, 5, 2];
expect(sentinalLinearSearch(array, 10)).toEqual([]);
expect(sentinalLinearSearch(array, 1)).toEqual([0, 5]);
expect(sentinalLinearSearch(array, 2)).toEqual([1, 4, 7]);
});
it('should search all strings in array', () => {
const array = ['a', 'b', 'a', 'c', 'd', 'a', 'r'];
expect(sentinalLinearSearch(array, 'c')).toEqual([3]);
expect(sentinalLinearSearch(array, 'b')).toEqual([1]);
expect(sentinalLinearSearch(array, 'a')).toEqual([0, 2, 5]);
});
});

View File

@ -0,0 +1,32 @@
import Comparator from '../../../utils/comparator/Comparator';
/**
* Sentinal Linear search implementation.
*
* @param {*[]} array
* @param {*} seekElement
* @param {function(a, b)} [comparatorCallback]
* @return {number[]}
*/
export default function sentinalLinearSearch(array, seekElement, comparatorCallback) {
const comparator = new Comparator(comparatorCallback);
const foundIndices = [];
const lastEle = array[array.length - 1]; // Picking the last element in the array
const i = 0;
while (comparator.notEqual(i, array.length - 1)) {
while(comparator.notEqual(array[i], seekElement)) {
i = i + 1;
}
if(comparator.notEqual(i, array.length - 1)) {
foundIndices.push(i);
i = i + 1;
}
}
array[array.length - 1] = lastEle; // Replacing the last element
if (comparator.equal(array[array.length - 1], seekElement)) {
foundIndices.push(i);
}
return foundIndices;
}