Skip to content

Commit

Permalink
Add binary search algorithm
Browse files Browse the repository at this point in the history
  • Loading branch information
Samayel committed Nov 20, 2015
1 parent eaab934 commit 17ef7e3
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 2 deletions.
2 changes: 2 additions & 0 deletions src/Algorithm/algorithm.jl
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,6 @@ using Reexport.@reexport

@reexport using SortingAlgorithms

include("binarysearch.jl")

end
22 changes: 22 additions & 0 deletions src/Algorithm/binarysearch.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
export binarysearch

binarysearch{T<:Integer}(f, z, α::T, β::T) = begin
if β - α == 1
y = f(α)
y == z && return α, α
y > z && throw(DomainError())

y = f(β)
y == z && return β, β
y < z && throw(DomainError())

return α, β
end

m =+ β) >> 1
y = f(m)

y > z && return binarysearch(f, z, α, m)
y < z && return binarysearch(f, z, m, β)
return m, m
end
5 changes: 3 additions & 2 deletions test/Algorithm/algorithm.jl
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@ module Algorithm
using Brainstorm.Algorithm
using Base.Test

include("binarysearch.jl")

function test_all()
println("")
print(rpad("Algorithm...", 50, ' '))

println("PASS")
test_binarysearch_all()
end

end
11 changes: 11 additions & 0 deletions test/Algorithm/binarysearch.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
function test_binarysearch_all()
print(rpad("Algorithm.BinarySearch...", 50, ' '))

@test [binarysearch(x -> x, i, 1, 100) for i in 1:100] == [(i,i) for i in 1:100]
@test [binarysearch(x -> 2x, i, 0, 10) for i in 2:10] == [(1,1); (1,2); (2,2); (2,3); (3,3); (3,4); (4,4); (4,5); (5,5)]

@test_throws DomainError binarysearch(x -> x, 0, 1, 10)
@test_throws DomainError binarysearch(x -> x, 11, 1, 10)

println("PASS")
end

0 comments on commit 17ef7e3

Please sign in to comment.