Anonymous user
Binary search: Difference between revisions
→{{header|Julia}}
(→{{header|PARI/GP}}: Add a more manual approach that the task was probably expecting) |
|||
Line 2,107:
2
=={{header|Julia}}==
{{works with|Julia|0.6}}
'''Iterative''':
<lang julia># Iterative
function binarysearch(lst::Vector{T}, val::T) where T
low = 1
high = length(
while low
mid =
if
high = mid - 1
elseif
low = mid + 1
else
return mid
end
end
end</lang>
'''Recursive'''
<lang
if isempty(lst) return 0 end
if low ≥ high
l==[] && (return -1)▼
if low >
else
mid = int((low+high)/2)▼
l[mid] > value ? (return binary_search(l, value, low, mid-1)) :▼
end
l[mid] < value ? (return binary_search(l, value, mid+1, high)) :▼
if lst[mid] > value
elseif lst[mid] < value
else
return mid
end
end</lang>
|