Avatar of paulfioravanti

paulfioravanti's solution

to Binary Search in the Elm Track

Published at Aug 14 2019 · 0 comments
Instructions
Test suite
Solution

Implement a binary search algorithm.

Searching a sorted collection is a common task. A dictionary is a sorted list of word definitions. Given a word, one can find its definition. A telephone book is a sorted list of people's names, addresses, and telephone numbers. Knowing someone's name allows one to quickly find their telephone number and address.

If the list to be searched contains more than a few items (a dozen, say) a binary search will require far fewer comparisons than a linear search, but it imposes the requirement that the list be sorted.

In computer science, a binary search or half-interval search algorithm finds the position of a specified input value (the search "key") within an array sorted by key value.

In each step, the algorithm compares the search key value with the key value of the middle element of the array.

If the keys match, then a matching element has been found and its index, or position, is returned.

Otherwise, if the search key is less than the middle element's key, then the algorithm repeats its action on the sub-array to the left of the middle element or, if the search key is greater, on the sub-array to the right.

If the remaining array to be searched is empty, then the key cannot be found in the array and a special "not found" indication is returned.

A binary search halves the number of items to check with each iteration, so locating an item (or determining its absence) takes logarithmic time. A binary search is a dichotomic divide and conquer search algorithm.

Elm Installation

Refer to the Installing Elm page for information about installing elm.

Writing the Code

The first time you start an exercise, you'll need to ensure you have the appropriate dependencies installed. Thankfully, Elm makes that easy for you and will install dependencies when you try to run tests or build the code.

Execute the tests with:

$ elm-test

Automatically run tests again when you save changes:

$ elm-test --watch

As you work your way through the test suite, be sure to remove the skip <| calls from each test until you get them all passing!

Source

Wikipedia http://en.wikipedia.org/wiki/Binary_search_algorithm

Submitting Incomplete Solutions

It is possible to submit an incomplete solution so you can see how others have completed the exercise.

Tests.elm

module Tests exposing (tests)

import Array
import BinarySearch exposing (find)
import Expect
import Fuzz exposing (Fuzzer)
import Test exposing (Test, describe, skip, test)


tests : Test
tests =
    describe "binarySearch"
        [ test "finds a value in an array with one element" <|
            \() ->
                Array.fromList [ 6 ]
                    |> find 6
                    |> Expect.equal (Just 0)
        , skip <|
            test "finds a value in the middle of an array" <|
                \() ->
                    Array.fromList [ 1, 3, 4, 6, 8, 9, 11 ]
                        |> find 6
                        |> Expect.equal (Just 3)
        , skip <|
            test "finds a value at the beginning of an array" <|
                \() ->
                    Array.fromList [ 1, 3, 4, 6, 8, 9, 11 ]
                        |> find 1
                        |> Expect.equal (Just 0)
        , skip <|
            test "finds a value in an array of odd length" <|
                \() ->
                    Array.fromList [ 1, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 634 ]
                        |> find 144
                        |> Expect.equal (Just 9)
        , skip <|
            test "finds a value in an array of even length" <|
                \() ->
                    Array.fromList [ 1, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377 ]
                        |> find 21
                        |> Expect.equal (Just 5)
        , skip <|
            test "identifies that a value is not included in the array" <|
                \() ->
                    Array.fromList [ 1, 3, 4, 6, 8, 9, 11 ]
                        |> find 7
                        |> Expect.equal Nothing
        , skip <|
            test "a value smaller than the array's smallest value is not included" <|
                \() ->
                    Array.fromList [ 1, 3, 4, 6, 8, 9, 11 ]
                        |> find 0
                        |> Expect.equal Nothing
        , skip <|
            test "a value larger than the array's largest value is not included" <|
                \() ->
                    Array.fromList [ 1, 3, 4, 6, 8, 9, 11 ]
                        |> find 13
                        |> Expect.equal Nothing
        , skip <|
            test "nothing is included in an empty array" <|
                \() ->
                    Array.empty
                        |> find 1
                        |> Expect.equal Nothing
        ]
module BinarySearch exposing (find)

import Array exposing (Array)


find : Int -> Array Int -> Maybe Int
find target xs =
    if Array.isEmpty xs then
        Nothing

    else
        let
            rightIndex =
                Array.length xs - 1
        in
        search target 0 rightIndex xs



-- PRIVATE


search : Int -> Int -> Int -> Array Int -> Maybe Int
search target left right xs =
    case compare left right of
        {- NOTE: This condition is met when search options have been exhausted,
           and the `left` index will have been incremented, or the `right` index
           decremented, to a number where we would be attempting to perform an
           "out-of-bounds" search on position `left` of a "sub-array" of length
           `right`.
        -}
        GT ->
            Nothing

        _ ->
            let
                middleIndex =
                    (left + right) // 2
            in
            case Array.get middleIndex xs of
                Nothing ->
                    Nothing

                Just middleElement ->
                    case compare middleElement target of
                        GT ->
                            search target left (middleIndex - 1) xs

                        LT ->
                            search target (middleIndex + 1) right xs

                        EQ ->
                            Just middleIndex

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?