Ideas
- Iterate over the array
- Find the target element and return its subscript
- After the traversal is over, if the target value is not found, return
-1
Time complexity : O(n)
achieve
Existing array [7, 5, 4, 15, 3, 9, 6, 12]
, search sequentially 3
:
Array.prototype.sequentialSearch = function(item) {
for (let i = 0; i < this.length; i++) {
if (this[i] === item) return i;
}
return -1;
};
const res = [7, 5, 4, 15, 3, 9, 6, 12].sequentialSearch(3);
console.log(res);
Results of the: