Skip to content

Instantly share code, notes, and snippets.

@afshin
Created January 21, 2012 14:16
Show Gist options
  • Save afshin/1652897 to your computer and use it in GitHub Desktop.
Save afshin/1652897 to your computer and use it in GitHub Desktop.
"single statement" … quescol (nested ternaries) binary search
Array.prototype.search = function (x, l, h, m) {
//returns an index >= 0 if arr.search(x) is found
//returns a negative index if arr.search(x) is not found
//if arr.search(x) < 0, Math.floor(-1 * arr.search(x)) is how many items in arr are smaller than x
return arguments.length < 4 ? this.search(x, 0, this.length - 1, Math.floor((this.length - 1) / 2))
: h < l ? l === 0 ? -0.1 : -1 * l
: this[m] < x ? this.search(x, m + 1, h, m + 1 + Math.floor((h - (m + 1)) / 2))
: this[m] > x ? this.search(x, l, m - 1, l + Math.floor((m - 1 - l) / 2))
: m;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment