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

Commit

Permalink
Haskell implement ternary search (#5625)
Browse files Browse the repository at this point in the history
* Solves issue with swift not finding the largest two elements correctly

* Solves  #5560 Write a Scala program to convert temperature from celsius to kelvin

* Removes #5560 changes

* F# program to implement linear search (#5295)

* Solves 5173: Write a Haskell program to find the largest three elements in an array

* Create implement_ternary_search.hs

Defines a function 'ternarySearch' that implements the ternary search algorithm.

---------

Co-authored-by: David Fernandez <david@Davids-MacBook-Pro.local>
Co-authored-by: Harsh Raj <harshraj8843@gmail.com>
Co-authored-by: Anandha Krishnan S <anandajith@gmail.com>
Co-authored-by: Yuri Cunha <isyuricunha@duck.com>
  • Loading branch information
5 people authored Apr 11, 2024
1 parent 30870c3 commit 63a86ff
Showing 1 changed file with 25 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
ternarySearch :: Ord a => [a] -> a -> Int -> Int -> Maybe Int
ternarySearch arr value l r
| l > r = Nothing
| otherwise =
let partitionSize = (r - l) `div` 3
mid1 = l + partitionSize
mid2 = r - partitionSize
in if (arr !! mid1) == value then Just mid1
else if (arr !! mid2) == value then Just mid2
else if value < (arr !! mid1) then ternarySearch arr value l (mid1 - 1)
else if value > (arr !! mid2) then ternarySearch arr value (mid2 + 1) r
else ternarySearch arr value (mid1 + 1) (mid2 - 1)

-- Helper function to handle 0-based indexing
ternarySearchWrapper :: Ord a => [a] -> a -> Maybe Int
ternarySearchWrapper arr value = ternarySearch arr value 0 (length arr - 1)

main :: IO ()
main = do
let list = [1,2,3,4,5]
value = 4
result = ternarySearchWrapper list value
case result of
Just index -> putStrLn $ "Element found at index: " ++ show index
Nothing -> putStrLn "Element not found in the array"

0 comments on commit 63a86ff

Please sign in to comment.