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

Binary search in F# added #5729

Merged
merged 1 commit into from
Jun 25, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions program/program/implement-binary-search/ImplementBinarySearch.fs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
let rec binarySearch (arr: 'a[]) (x: 'a) (lowerBound: int) (upperBound: int) : int =
if upperBound < lowerBound then
-1 // x does not exist
else
let midPoint = lowerBound + (upperBound - lowerBound) / 2
if arr.[midPoint] < x then
binarySearch arr x (midPoint + 1) upperBound
elif arr.[midPoint] > x then
binarySearch arr x lowerBound (midPoint - 1)
else
midPoint // x found at midPoint

// Example usage
let arr = [|2; 3; 4; 10; 40|]
let x = 10
let result = binarySearch arr x 0 (Array.length arr - 1)
if result <> -1 then
printfn "Element %d is present at index %d" x result
else
printfn "Element %d is not present in array" x