bsearch-ruby 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. data/bsearch.rb +20 -0
  2. data/test_bsearch.rb +22 -0
  3. metadata +48 -0
@@ -0,0 +1,20 @@
1
+ # Binary search algorithm
2
+ module BSearch
3
+ VERSION = '0.1.1'
4
+
5
+ # Assume's haystack is an array of comparable objects
6
+ def self.bsearch(needle, haystack, first=0, last=nil)
7
+ last ||= haystack.size - 1
8
+ return nil if last < first # not found, or empty haystack
9
+
10
+ cur = first + (last - first)/2
11
+ case needle <=> haystack[cur]
12
+ when -1 # needle is smaller than cur value
13
+ bsearch(needle, haystack, first, cur-1)
14
+ when 1 # needle is larger than cur value
15
+ bsearch(needle, haystack, cur+1, last)
16
+ when 0
17
+ cur
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,22 @@
1
+ require 'test/unit'
2
+ require_relative 'bsearch'
3
+
4
+ class BSearchTest < Test::Unit::TestCase
5
+
6
+ def test_bsearch_results
7
+ ary = (0..9).to_a
8
+ ary.each do |i|
9
+ assert_equal i, BSearch.bsearch(i, ary)
10
+ end
11
+ end
12
+
13
+ def test_empty_haystack
14
+ assert_nil BSearch.bsearch(0, [])
15
+ end
16
+
17
+ def test_not_found
18
+ needles = [1,3,5,7]
19
+ haystack = [2,4,6]
20
+ needles.each{|n| assert_nil BSearch.bsearch(n, haystack) }
21
+ end
22
+ end
metadata ADDED
@@ -0,0 +1,48 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: bsearch-ruby
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.1
5
+ prerelease:
6
+ platform: ruby
7
+ authors:
8
+ - Aaron Suggs
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+ date: 2012-07-31 00:00:00.000000000 Z
13
+ dependencies: []
14
+ description: A binary search implementation in ruby
15
+ email: aaron@ktheory.com
16
+ executables: []
17
+ extensions: []
18
+ extra_rdoc_files: []
19
+ files:
20
+ - bsearch.rb
21
+ - test_bsearch.rb
22
+ homepage: https://gist.github.com/3219940
23
+ licenses: []
24
+ post_install_message:
25
+ rdoc_options:
26
+ - --charset=UTF-8
27
+ require_paths:
28
+ - .
29
+ required_ruby_version: !ruby/object:Gem::Requirement
30
+ none: false
31
+ requirements:
32
+ - - ! '>='
33
+ - !ruby/object:Gem::Version
34
+ version: 1.9.3
35
+ required_rubygems_version: !ruby/object:Gem::Requirement
36
+ none: false
37
+ requirements:
38
+ - - ! '>='
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ requirements: []
42
+ rubyforge_project:
43
+ rubygems_version: 1.8.24
44
+ signing_key:
45
+ specification_version: 3
46
+ summary: Binary search
47
+ test_files:
48
+ - test_bsearch.rb