Created
November 14, 2013 17:00
-
-
Save tekkoc/7470351 to your computer and use it in GitHub Desktop.
binary search
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import std.stdio; | |
| import std.range; | |
| import std.algorithm; | |
| void main() | |
| { | |
| writeln([3, 1, 6, 2].exists(6)); // true | |
| writeln([2, 3, 4, 5, 3].exists(6)); // false | |
| } | |
| bool exists(int[] xs, int needle) | |
| { | |
| bool f(int[] ys) | |
| { | |
| if (ys.empty) return false; | |
| auto i = ys.length / 2; | |
| if (ys[i] < needle) return f(ys[(i + 1)..$]); | |
| if (needle < ys[i]) return f(ys[0..i]); | |
| return true; | |
| } | |
| return f(xs.sort); | |
| } | |
| unittest | |
| { | |
| auto ns1 = [2, 5, 3, 4]; | |
| auto m1 = 5; | |
| assert(!ns1.find(m1).empty == ns1.exists(m1)); | |
| auto ns2 = [2, 5, 3, 4, 1]; | |
| auto m2 = 7; | |
| assert(!ns2.find(m2).empty == ns2.exists(m2)); | |
| auto ns3 = [1]; | |
| auto m3 = 1; | |
| assert(!ns3.find(m3).empty == ns3.exists(m3)); | |
| auto ns4 = [1]; | |
| auto m4 = 2; | |
| assert(!ns4.find(m4).empty == ns4.exists(m4)); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment