Skip to main content

Binary Search

Pass a sorted array of numbers/string along with the element which needs to be found.

Usage

src/sample/binarysearch.ts
import { binarySearch } from 'athro';

const arr = [2, 4, 6, 8];
const target = 6;

const result = binarySearch(arr, target)
Caution

Make sure the array passed is sorted. Binary Search algorithm only works on sorted arrays.

Time Complexity

The time complexity of Binary Search is:

CaseTime ComplexityDescription
BestO(1)When the element is found at the middle index
AverageO(log(n))When the elment is found at any index besides middle
WorstO(log(n))When the elment is found at any index besides middle