From 92800d9721e875626aaa055656d3a15b4c28781d Mon Sep 17 00:00:00 2001 From: Hugo Venega Date: Thu, 18 Nov 2021 16:20:41 -0300 Subject: [PATCH] Add binary search function and test it --- src/search/binarysearch/binarySearch.spec.ts | 28 ++++++++++++++++++++ src/search/binarysearch/binarySearch.ts | 18 +++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 src/search/binarysearch/binarySearch.spec.ts create mode 100644 src/search/binarysearch/binarySearch.ts diff --git a/src/search/binarysearch/binarySearch.spec.ts b/src/search/binarysearch/binarySearch.spec.ts new file mode 100644 index 0000000..798e92d --- /dev/null +++ b/src/search/binarysearch/binarySearch.spec.ts @@ -0,0 +1,28 @@ +import binarySearch from './binarySearch'; + +describe('binary Search', () => { + it(' should return null when the array is empty', () => { + const arrayToSearch: number[] = []; + expect(binarySearch(arrayToSearch, 44)).toEqual(null); + }); + + it('should return the element passed by parameter', () => { + const arrayToSearch = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; + expect(binarySearch(arrayToSearch, 4)).toEqual(4); + }); + + it('should return null when no found the element into the array', () => { + const arrayToSearch = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; + expect(binarySearch(arrayToSearch, 32)).toEqual(null); + }); + + it('should return should return the element when this is in the beginning of the array', () => { + const arrayToSearch = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; + expect(binarySearch(arrayToSearch, 1)).toEqual(1); + }); + + it('should return should return the element when this is in the end of the array', () => { + const arrayToSearch = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]; + expect(binarySearch(arrayToSearch, 16)).toEqual(16); + }); +}); diff --git a/src/search/binarysearch/binarySearch.ts b/src/search/binarysearch/binarySearch.ts new file mode 100644 index 0000000..76697f4 --- /dev/null +++ b/src/search/binarysearch/binarySearch.ts @@ -0,0 +1,18 @@ +export default function binarySearch(arr: number[], + val:number, + start = 0, + end = arr.length - 1):number | null { + const mid = Math.floor((start + end) / 2); + + if (val === arr[mid]) { + return val; + } + + if (start >= end) { + return null; + } + + return val < arr[mid] + ? binarySearch(arr, val, start, mid - 1) + : binarySearch(arr, val, mid + 1, end); +}