Skip to content

Commit 62c3b39

Browse files
coditoriegonSchiele
authored andcommitted
Add julialang binary search sample (egonSchiele#107)
* Add julialang binary search sample * Add unit test
1 parent 06ee65d commit 62c3b39

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
using Test
2+
3+
function binary_search(arr,item)
4+
low = 0
5+
high = length(arr)
6+
7+
while low <= high
8+
mid = (low + high) ÷ 2
9+
guess = 0
10+
try
11+
guess = arr[mid]
12+
catch
13+
return nothing
14+
end
15+
if guess == item
16+
return mid
17+
elseif guess > item
18+
high = mid - 1
19+
else
20+
low = mid + 1
21+
end
22+
end
23+
end
24+
25+
arr = [1,3,5,7,9]
26+
@test binary_search(arr,3) == 2
27+
@test binary_search(arr,-1) == nothing

0 commit comments

Comments
 (0)