Skip to content
Open
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
28 changes: 28 additions & 0 deletions src/search/binarysearch/binarySearch.spec.ts
Original file line number Diff line number Diff line change
@@ -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);
});
});
18 changes: 18 additions & 0 deletions src/search/binarysearch/binarySearch.ts
Original file line number Diff line number Diff line change
@@ -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);
}