Skip to content

Instantly share code, notes, and snippets.

@ramithuh
Last active September 22, 2016 08:01
Show Gist options
  • Save ramithuh/ce5c3dd3bb41152de16855465ebc5a08 to your computer and use it in GitHub Desktop.
Save ramithuh/ce5c3dd3bb41152de16855465ebc5a08 to your computer and use it in GitHub Desktop.
Examples with coffeescript
### The implementation of binary search that is tested.
# Return the index of an element in a sorted list. (or -1, if not present)###
index = (list, target) ->
[low, high] = [0, list.length]
while low < high
mid = (low + high) >> 1
val = list[mid]
return mid if val is target
if val < target then low = mid + 1 else high = mid
return -1
console.log 2 is index [10, 20, 30, 40, 50], 30
console.log 4 is index [-97, 35, 67, 88, 1200], 1200
console.log 0 is index [0, 45, 70], 0
_______________________________________________________
/* The implementation of binary search that is tested.
* Return the index of an element in a sorted list. (or -1, if not present)
*/
var index;
index = function(list, target) {
var high, low, mid, ref, val;
ref = [0, list.length], low = ref[0], high = ref[1];
while (low < high) {
mid = (low + high) >> 1;
val = list[mid];
if (val === target) {
return mid;
}
if (val < target) {
low = mid + 1;
} else {
high = mid;
}
}
return -1;
};
console.log(2 === index([10, 20, 30, 40, 50], 30));
console.log(4 === index([-97, 35, 67, 88, 1200], 1200));
console.log(0 === index([0, 45, 70], 0));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment