Skip to content

Instantly share code, notes, and snippets.

@dciccale
Last active December 22, 2015 03:49
Show Gist options
  • Select an option

  • Save dciccale/6413107 to your computer and use it in GitHub Desktop.

Select an option

Save dciccale/6413107 to your computer and use it in GitHub Desktop.

Revisions

  1. dciccale revised this gist Sep 3, 2013. 1 changed file with 1 addition and 2 deletions.
    3 changes: 1 addition & 2 deletions demo.html
    Original file line number Diff line number Diff line change
    @@ -4,7 +4,6 @@
    <script>
    var binarySearch = function(b,e){for(var c=0,d=b.length,a;c<=d;){a=~~((d+c)/2);if(b[a]===e)return a;b[a]>e?d=a-1:c=a+1}return-1};
    var items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
    var value = 'i';
    var result = binarySearch(items, value);
    var result = binarySearch(items, 'i');
    console.log(result); // logs 8
    </script>
  2. dciccale created this gist Sep 2, 2013.
    3 changes: 3 additions & 0 deletions README.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,3 @@
    # binarySearch

    Tiny binary search done with 109 bytes of JavaScript.
    12 changes: 12 additions & 0 deletions binarysearch.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,12 @@
    /**
    * @param a A list of items
    * @param b An item to search its index inside the list of items
    */
    function binarySearch(a, b) {
    for (var c = 0, d = a.length, e; c <= d;) {
    e = ~~((d + c) / 2);
    if (a[e] === b) return e;
    a[e] > b ? d = e - 1 : c = e + 1
    }
    return -1;
    }
    1 change: 1 addition & 0 deletions binarysearch.min.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1 @@
    function(b,e){for(var c=0,d=b.length,a;c<=d;){a=~~((d+c)/2);if(b[a]===e)return a;b[a]>e?d=a-1:c=a+1}return-1}
    10 changes: 10 additions & 0 deletions demo.html
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,10 @@
    <!doctype html>
    <title>Demo</title>

    <script>
    var binarySearch = function(b,e){for(var c=0,d=b.length,a;c<=d;){a=~~((d+c)/2);if(b[a]===e)return a;b[a]>e?d=a-1:c=a+1}return-1};
    var items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
    var value = 'i';
    var result = binarySearch(items, value);
    console.log(result); // logs 8
    </script>