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

Jump Search program in F# added #5723

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
35 changes: 35 additions & 0 deletions program/program/implement-jump-search/ImplementJumpSearch.fs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
open System

let jumpSearch (arr: 'a[]) (x: 'a) (comparer: 'a -> 'a -> int) =
let n = arr.Length
let step = int (Math.Floor(Math.Sqrt(float n)))
let mutable prev = 0

// Finding the block where element is present
while prev < n && comparer arr.[Math.Min(step, n) - 1] x < 0 do
prev <- step
step <- step + int (Math.Floor(Math.Sqrt(float n)))
if prev >= n then
return -1 // Element not found

// Linear search for x in block beginning with prev
while prev < n && comparer arr.[prev] x < 0 do
prev <- prev + 1
if prev = Math.Min(step, n) then
return -1 // Element not found

// If element is found
if prev < n && comparer arr.[prev] x = 0 then
prev
else
-1 // Element not found

// Example usage
let arr = [|0; 1; 2; 3; 4; 5; 6; 7; 8; 9; 10|]
let x = 7
let result = jumpSearch arr x compare

if result <> -1 then
printfn "Element %d is at index %d" x result
else
printfn "Element %d is not present in the array" x