Created
October 1, 2013 06:15
-
-
Save DavidRagone/6774489 to your computer and use it in GitHub Desktop.
Binary search, TDD
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
| require 'rspec' | |
| class Array | |
| def binary_search(value, index = 0) | |
| middle = self[size/2] | |
| if middle == value | |
| index + size/2 | |
| elsif size == 1 | |
| -1 | |
| elsif middle < value | |
| self[(size/2 + 1)..-1].binary_search(value, index + size/2 + 1) | |
| else | |
| self[0..(size/2 - 1)].binary_search(value, index) | |
| end | |
| end | |
| end | |
| describe Array do | |
| describe "#binary_search" do | |
| let(:array) { %w(a b c d e f g h i j k l m n oh-hai p q r s t u v w x y z) } | |
| subject { array.binary_search(value) } | |
| context "not found" do | |
| let(:value) { 'not there' } | |
| it "returns -1" do | |
| should eq -1 | |
| end | |
| end | |
| context "found" do | |
| context "middle" do | |
| let(:value) { 'n' } | |
| it 'returns the index' do | |
| should eq 13 | |
| end | |
| end | |
| context "somewhere else" do | |
| let(:value) { 'oh-hai' } | |
| it "returns the index" do | |
| should eq 14 | |
| end | |
| end | |
| end | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment