Skip to content

Instantly share code, notes, and snippets.

@karol-majewski
Last active July 7, 2020 13:20
Show Gist options
  • Save karol-majewski/b6e221c434f97ea05ccd7b804e6a7995 to your computer and use it in GitHub Desktop.
Save karol-majewski/b6e221c434f97ea05ccd7b804e6a7995 to your computer and use it in GitHub Desktop.
Easy binary search in TypeScript
type Comparator<T> = (x: T, y: T) => Comparison;
enum Comparison {
LessThan = -1,
Equal = 0,
GreaterThan = 1,
}
function search<T>(array: T[], item: T, compare: Comparator<T>): number {
let [left, right] = [0, array.length - 1];
while (left <= right) {
let middle = Math.floor((left + right) / 2);
switch (compare(array[middle], item)) {
case Comparison.Equal:
return middle;
case Comparison.LessThan:
left = middle + 1;
break;
case Comparison.GreaterThan:
right = middle - 1;
break;
}
}
return -1;
}
const comparator: Comparator<number> = (left, right) => {
if (left === right) {
return Comparison.Equal;
} else if (left < right) {
return Comparison.LessThan
} else {
return Comparison.GreaterThan
}
}
search([0, 1, 2, 3, 4], 2, comparator);
@karol-majewski
Copy link
Author

Another solution:

type Comparator<T> = (x: T, y: T) => Comparison;

enum Comparison {
  LessThan = -1,
  Equal = 0,
  GreaterThan = 1,
}

class SortedArray<T> extends Array<T> {
  #brand = Symbol();

  constructor(elements: T[], comparator: Comparator<T>) {
    super(...elements.slice().sort(comparator))
  }
}

function search<T>(array: SortedArray<T>, item: T): number {
  let [left, right] = [0, array.length - 1];

  while (left <= right) {
    let middleIndex = Math.floor((left + right) / 2);

    if (array[middleIndex] === item) {
      return middleIndex;
    }

    if (array[middleIndex] < item) {
      left = middleIndex + 1;
    } else {
      right = middleIndex -1
    }
  }

  return -1;
}

const comparator: Comparator<number> = (left, right) => {
  if (left === right) {
    return Comparison.Equal;
  } else if (left < right) {
    return Comparison.LessThan
  } else {
    return Comparison.GreaterThan
  }
}

search(new SortedArray([5, 1, 4, 9, Math.E], comparator), 4);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment