Skip to content

Instantly share code, notes, and snippets.

@9bany
Created November 12, 2021 07:03
Show Gist options
  • Save 9bany/67bf69386f8d799597d5b5138f70e2eb to your computer and use it in GitHub Desktop.
Save 9bany/67bf69386f8d799597d5b5138f70e2eb to your computer and use it in GitHub Desktop.
Binary Search - Javascript
function banarySearch(key, arr, min, max, callBack) {
if (min >= max) {
return undefined;
}
const midIndex = parseInt(min + (max - min) / 2, 0.0);
const result = callBack(arr[midIndex]);
if (result > key) {
return banarySearch(key, arr, min, midIndex, callBack);
} else if (result < key) {
return banarySearch(key, arr, midIndex + 1, max, callBack);
} else {
return midIndex;
}
}
@9bany
Copy link
Author

9bany commented Nov 12, 2021

Usage

class Struct {
  constructor(id) {
    this.id = id;
  }
}

let listStructs = [
  new Struct(0),
  new Struct(1),
  new Struct(2),
  new Struct(3),
  new Struct(4),
  new Struct(5),
  new Struct(6),
  new Struct(7),
  new Struct(8),
  new Struct(9),
  new Struct(10),
  new Struct(11)
];

let result = banarySearch(
  1,
  listStructs,
  0,
  listStructs.length,
  function callBack(item) {
    return item.id;
  }
);

console.log(listStructs[result]);

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