diff --git a/Search/LinearSearch.ts b/Search/LinearSearch.ts new file mode 100644 index 00000000..ae03288a --- /dev/null +++ b/Search/LinearSearch.ts @@ -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; +} \ No newline at end of file diff --git a/Search/test/LinearSearch.test.ts b/Search/test/LinearSearch.test.ts new file mode 100644 index 00000000..71021022 --- /dev/null +++ b/Search/test/LinearSearch.test.ts @@ -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) + }, + ); +});