mirror of
https://github.moeyy.xyz/https://github.com/trekhleb/javascript-algorithms.git
synced 2024-11-10 11:09:43 +08:00
Merge 7e454924de
into ca3d16dcce
This commit is contained in:
commit
088a8a3a57
9
src/algorithms/search/sentinal-linear-search/README.md
Normal file
9
src/algorithms/search/sentinal-linear-search/README.md
Normal 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)
|
@ -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]);
|
||||
});
|
||||
});
|
@ -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;
|
||||
}
|
Loading…
Reference in New Issue
Block a user