ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Strictly Typed Binary Search for Ordered Arrays

TypeScript

Goal -- WPM

Ready
Exercise Algorithm Area
1/**
2* Performs a binary search on a sorted array of elements.
3* Assumes the array is sorted in ascending order.
4*
5* @template T The type of elements in the array, must be comparable.
6* @param {T[]} arr The sorted array to search within.
7* @param {T} target The value to search for.
8* @returns {number} The index of the target element if found, otherwise -1.
9*/
10function binarySearch<T extends number | string>(arr: T[], target: T): number {
11if (!arr || arr.length === 0) {
12return -1; // Handle empty array edge case
13}
14
15let low = 0;
16let high = arr.length - 1;
17
18while (low <= high) {
19// Calculate mid point to avoid potential overflow
20const mid = Math.floor(low + (high - low) / 2);
21const midValue = arr[mid];
22
23if (midValue === target) {
24return mid; // Target found
25} else if (midValue < target) {
26low = mid + 1; // Search in the right half
27} else {
28high = mid - 1; // Search in the left half
29}
30}
31
32return -1; // Target not found
33}
34
35/**
36* Helper function to check if an array is sorted (for testing purposes).
37* Not part of the core binary search logic but useful for validation.
38*/
39function isSorted<T>(arr: T[]): boolean {
40for (let i = 0; i < arr.length - 1; i++) {
41if (arr[i] > arr[i + 1]) {
42return false;
43}
44}
45return true;
46}
Algorithm description viewbox

Strictly Typed Binary Search for Ordered Arrays

Algorithm description:

This function implements a classic binary search algorithm designed for sorted arrays. It efficiently finds the index of a target element by repeatedly dividing the search interval in half. This is commonly used in applications requiring fast lookups in large, ordered datasets, such as searching for a word in a dictionary or a product in an indexed catalog.

Algorithm explanation:

The binary search algorithm operates on a sorted array by maintaining a search interval defined by `low` and `high` indices. In each iteration, it calculates the middle index and compares the element at `mid` with the `target`. If `midValue` equals `target`, the index is returned. If `midValue` is less than `target`, the search continues in the right half by setting `low` to `mid + 1`. Otherwise, the search continues in the left half by setting `high` to `mid - 1`. The loop terminates when `low` exceeds `high`, indicating the target is not present. The time complexity is O(log n) because the search space is halved in each step. The space complexity is O(1) as it uses a constant amount of extra space. Edge cases like empty arrays and single-element arrays are handled. The invariant is that the target, if present, always lies within the `[low, high]` range.

Pseudocode:

function binarySearch(arr, target):
  if arr is empty:
    return -1

  low = 0
  high = arr.length - 1

  while low <= high:
    mid = floor(low + (high - low) / 2)
    midValue = arr[mid]

    if midValue == target:
      return mid
    else if midValue < target:
      low = mid + 1
    else:
      high = mid - 1

  return -1