diff --git a/snippets_archive/binarySearch.md b/snippets_archive/binarySearch.md deleted file mode 100644 index c68b19b87..000000000 --- a/snippets_archive/binarySearch.md +++ /dev/null @@ -1,27 +0,0 @@ ---- -title: binarySearch -tags: algorithm,beginner ---- - -Use recursion. Similar to `Array.prototype.indexOf()` that finds the index of a value within an array. -The difference being this operation only works with sorted arrays which offers a major performance boost due to it's logarithmic nature when compared to a linear search or `Array.prototype.indexOf()`. - -Search a sorted array by repeatedly dividing the search interval in half. -Begin with an interval covering the whole array. -If the value of the search is less than the item in the middle of the interval, recurse into the lower half. Otherwise recurse into the upper half. -Repeatedly recurse until the value is found which is the mid or you've recursed to a point that is greater than the length which means the value doesn't exist and return `-1`. - -```js -const binarySearch = (arr, val, start = 0, end = arr.length - 1) => { - if (start > end) return -1; - const mid = Math.floor((start + end) / 2); - if (arr[mid] > val) return binarySearch(arr, val, start, mid - 1); - if (arr[mid] < val) return binarySearch(arr, val, mid + 1, end); - return mid; -}; -``` - -```js -binarySearch([1, 4, 6, 7, 12, 13, 15, 18, 19, 20, 22, 24], 6); // 2 -binarySearch([1, 4, 6, 7, 12, 13, 15, 18, 19, 20, 22, 24], 21); // -1 -``` \ No newline at end of file diff --git a/test/binarySearch.test.js b/test/binarySearch.test.js deleted file mode 100644 index 4291f4885..000000000 --- a/test/binarySearch.test.js +++ /dev/null @@ -1,17 +0,0 @@ -const {binarySearch} = require('./_30s.js'); - -test('binarySearch is a Function', () => { - expect(binarySearch).toBeInstanceOf(Function); -}); -test('Finds item in array', () => { - expect(binarySearch([1, 4, 6, 7, 12, 13, 15, 18, 19, 20, 22, 24], 6)).toBe(2); -}); -test('Returns -1 when not found', () => { - expect(binarySearch([1, 4, 6, 7, 12, 13, 15, 18, 19, 20, 22, 24], 21)).toBe(-1); -}); -test('Works with empty arrays', () => { - expect(binarySearch([], 21)).toBe(-1); -}); -test('Works for one element arrays', () => { - expect(binarySearch([1], 1)).toBe(0); -});