# Code for Binary Search Algorithm (Julia)

What does Binary Search Algorithm do? Given a sorted array of n elements, write a function to search for the index of a given element (target).

## Process of working of Binary Search Algorithm?

• Search for the array by dividing the array in half repeatedly.
• Initially consider the actual array and pick the element at the middle index
• Keep a lower index i.e. 0 and higher index i.e. length of array
• If it is equal to the target element then return the index
• Else if it is greater than the target element then consider only the left half of array. (lower index = 0, higher = middle – 1)
• Else if it is less than the target element then consider only the right half of array. (lower index = middle + 1, higher = length of array)
• Return -(insertion index + 1) if the target element is not found in the array (If the lower index is greater than or equal to higher index). Some simpler implementations just return -1 if the element is not found. The offset of 1 must be added as the insertion index might be 0 (the searched value might be smaller than all elements in the array). As indexing starts at 0, this must be distinguishable from the case where the target element has the index 0.

## Time Complexity of Binary Search Algorithm

• O(log n) Worst Case
• O(1) Best Case (If middle element of initial array is the target element)

## Space Complexity of Binary Search Algorithm

• O(1) For iterative approach
• O(1) For recursive approach if tail call optimization is used, O(log n) due to recursion call stack, otherwise

## Python Code for Binary Search Algorithm

For copying this code to your local Code Editor please click little arrow on top right corner just next to “Binary Search Algorithm” and then hit Command + C if your on Mac or Control + C if your on Windows. This will copy the code to your laptop’s Clipboard and then you can go to your local Code Editor and paste it.

``````"""
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 the range of indices that equal the search key value are
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. Search methods in Julia typically return an empty range located at the insertion
point in this case. 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.
"""
function binary_search(list, query; rev=false, lt=<, by=identity)
if issorted(list) || issorted(list; rev=true)
low = !rev ? 1 : length(list)
high = !rev ? length(list) : 1
middle(l, h) = round(Int, (l + h)//2)
query = by(query)

while !rev ? low <= high : high <= low
mid = middle(low, high)
by(list[mid]) === query && return mid:mid
if lt(by(list[mid]), query)
low = !rev ? mid + 1 : mid - 1
else
high = !rev ? mid - 1 : mid + 1
end
end
return !rev ? (low:high) : (high:low)

else
throw(error("List not sorted, unable to search value"))
end
end

"""
binary_search(arr::AbstractArray{T,1}, l::T, r::T, x::T) where {T<:Real}
The implementation of this binary Search is recursive and requires O(Log n) space. With iterative Binary Search, we need only O(1) space. Useful for the implementation of `exponential_search`.
"""
function binary_search(arr::AbstractArray{T,1}, l::T, r::T, x::T) where {T<:Real}
if (r >= l)
mid = Int(ceil(l + (r - l) / 2))
# println(mid)
if (arr[mid] == x)
return "Element present at index \$mid"
elseif (arr[mid] > x)
binary_search(arr, l, mid - 1, x)
else
binary_search(arr, mid + 1, r, x)
end
else
return "Element not present in array"
end
end``````