Skip to content
This repository has been archived by the owner on Jul 10, 2024. It is now read-only.

Commit

Permalink
Binary search in Julia (#5727)
Browse files Browse the repository at this point in the history
Co-authored-by: Riyazul555 <[email protected]>
  • Loading branch information
Riyazul555 and MdRiyazulIslam authored Jun 10, 2024
1 parent 7dfab84 commit 06a1474
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions program/program/implement-binary-search/implement-binary-search.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
function binary_search(arr, x)
lower_bound = 1
upper_bound = length(arr)

while lower_bound <= upper_bound
mid_point = lower_bound + (upper_bound - lower_bound) ÷ 2

if arr[mid_point] < x
lower_bound = mid_point + 1
elseif arr[mid_point] > x
upper_bound = mid_point - 1
else
return mid_point # x found at mid_point
end
end

return -1 # x does not exist
end

# Example usage
arr = [2, 3, 4, 10, 40]
x = 10

result = binary_search(arr, x)
if result != -1
println("Element $x is present at index $result")
else
println("Element $x is not present in array")
end

0 comments on commit 06a1474

Please sign in to comment.