xonecas.io
2495
Xg

xonecas.github.com / files

xonecas.github.com / _posts / 2011-09-19-binary-search-twitter-size.markdown

898 bytes
1---
2layout: post
3title: Binary Searchy in less than 140 characters.
4---
5
6`function f(a,v,l,h){var m;return h<l ? !-1: a[(m=~~(l+(h-l)/2))]>v ? f(a,v,l, m-1): a[m] < v ? f(a,v,m+1,h): m; }`
7
8And it works too!
9
10Using the binary operator `~~` I'm able to ditch `Math.floor()` and I replaced `false` with `!-1`. After that, it will fit in 140 chars, with room to spare!
11
12Here's the **clean** implementation:
13
14{% highlight javascript %}
15    function fn (a, v, l, h) {
16        var m;
17        if (h < l) {
18            return false;
19        }
20
21        m = Math.floor(l + (h - l) / 2);
22
23        if (a[m] > v) {
24            return fn(a, v, l, m-1);
25        } else if (a[m] < v) {
26            return fn(a, v, m+1, h);
27        } else {
28            return m;
29        }
30    }
31{% endhighlight %}
32
33**UPDATE**: It was pointed out to me that I could have saved another character by using `!1` instead of using `!-1`