Skip to content

algorithm: linear search #75

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Oct 29, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions Search/LinearSearch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,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;
}
14 changes: 14 additions & 0 deletions Search/test/LinearSearch.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { linearSearch } from "../LinearSearch";

describe("Linear search", () => {
test.each([
[['o', 'b', 'c'], 'c', 2],
[[1, 2, 3, 4, 5], 4, 3],
[['s', 't', 'r', 'i', 'n', 'g'], 'a', -1]
])(
"of %o , searching for %o, expected %i",
(array: any[], target: any, index: number) => {
expect(linearSearch(array, target)).toStrictEqual(index)
},
);
});