Remove binarySearch

This commit is contained in:
Angelos Chalaris
2020-04-16 11:32:49 +03:00
parent 5de3a6526d
commit c244d9b903
2 changed files with 0 additions and 44 deletions

View File

@ -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
```

View File

@ -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);
});