Binary Search in Julia

Binary Search in Julia

  • Julia
  • 2 mins read

Binary search is an algorithm that is used to search for an element in a sorted array. It works by dividing the array into two halves, checking which half the target element is in, and then repeating the process on that half until the target is found. To implement binary search in Julia, you can use a function given in this post. The function takes in the sorted array arr and the target element target, and uses a while loop to divide the array in half and check if the target is in the left or right half. If the target is found, the function returns its index in the array. If the target is not found, the function returns -1.

Binary Search in Julia Example

Here is an example of how to implement binary search in Julia:

function binary_search(arr, target)
    low = 1
    high = length(arr)

    while low <= high
        mid = floor(Int, (low + high) / 2)
        if arr[mid] == target
            return mid
        elseif arr[mid] < target
            low = mid + 1
        else
            high = mid - 1
        end
    end

    return -1
end

# Test the function
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
target = 8

result = binary_search(arr, target)
println("The target was found at index: ", result)

If we run this code, we should see the following output:

The target was found at index: 8

This indicates that the target value 8 was found at index 8 in the array arr.