forked from TheAlgorithms/TypeScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinear_search.ts
More file actions
18 lines (18 loc) · 766 Bytes
/
linear_search.ts
File metadata and controls
18 lines (18 loc) · 766 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* @function linearSearch
* @description linear search is the simplest search possible in a array
* it has a linear cost, if the value is present in the array, then the index of the first occurence will be returned
* if it's not present, the return it will be -1
* @param {number[]} array - list of numbers
* @param {number} target - target number to search for
* @return {number} - index of the target number in the list, or -1 if not found
* @see https://en.wikipedia.org/wiki/Linear_search\
* @example linearSearch([1,2,3,5], 3) => 2
* @example linearSearch([1,5,6], 2) => -1
*/
export const linearSearch = (array: any[], target: any): number => {
for (let i = 0; i < array.length; i++) {
if (array[i] === target) return i
}
return -1
}