Binary Search

May 23, 2023

DSA & Leetcodes

Binary Search

Thuta Sann

Thuta Sann

In this Algorithm section, I will demonstrate the Binary Search Algorithm.


Share This Snippet To :

Binary Search

Binary Search is defined as a searching algorithm used in a sorted array by repeatedly dividing the search interval in half.
export function binarySearch(value: number, numbers: number[]): number { let left = 0; let right = numbers.length - 1; let resultIndex = -1; while (left <= right) { let mid = Math.round(left + (right - left) / 2); if (numbers[mid] === value) { resultIndex = mid; break; } else { if (numbers[mid]! > value) { right = mid - 1; } else { left = mid + 1; } } } return resultIndex; } // Usage const BiNumbers: number[] = [1, 5, 7, 64, 777, 1000, 1002, 1003]; console.log('Found number at: ' + binarySearch(64, BiNumbers));

Cookie

I baked some cookies that you have to accept, if you want to enjoy my portfolio.
In order to gather information and make improvements, I should use some third-party cookies too, Can I?