ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Elixir: Implement Binary Search on Sorted List

Elixir

Goal -- WPM

Ready
Exercise Algorithm Area
1defmodule SearchAlgorithms do
2@moduledoc """
3Provides various search algorithms.
4"""
5
6@doc """
7Performs an iterative binary search on a sorted list of integers.
8
9It repeatedly divides the search interval in half. If the value of the
10search key is less than the item in the middle of the interval, narrow
11the interval to the lower half. Otherwise, narrow it to the upper half.
12Repeatedly check until the value is found or the interval is empty.
13
14Examples:
15
16iex> SearchAlgorithms.iterative_binary_search([1, 3, 5, 7, 9, 11, 13], 7)
17{:ok, 3}
18
19iex> SearchAlgorithms.iterative_binary_search([1, 3, 5, 7, 9, 11, 13], 6)
20:not_found
21
22iex> SearchAlgorithms.iterative_binary_search([], 5)
23:not_found
24
25iex> SearchAlgorithms.iterative_binary_search([5], 5)
26{:ok, 0}
27
28iex> SearchAlgorithms.iterative_binary_search([5], 10)
29:not_found
30"""
31def iterative_binary_search(sorted_list, target) do
32# Handle empty list edge case.
33if Enum.empty?(sorted_list) do
34:not_found
35else
36# Initialize search boundaries.
37low = 0
38high = length(sorted_list) - 1
39# Call the iterative helper function.
40perform_search(sorted_list, target, low, high)
41end
42end
43
44# Helper function to perform the iterative binary search.
45defp perform_search(sorted_list, target, low, high) do
46# Loop while the search interval is valid.
47# The condition `low <= high` ensures we check all possible positions.
48if low <= high do
49# Calculate the middle index, avoiding potential overflow.
50mid = low + div(high - low, 2)
51
52# Get the element at the middle index.
53# We use `Enum.at` which is O(N) for lists, but for this exercise,
54# we assume it's a conceptual binary search on a list structure.
55# In a real-world scenario, use a data structure with O(1) access like Array or Vector.
56middle_element = Enum.at(sorted_list, mid)
57
58# Compare the middle element with the target.
59cond do
60middle_element == target ->
61# Target found, return its index.
62{:ok, mid}
63middle_element < target ->
64# Target is in the right half, adjust low boundary.
65# The new low is `mid + 1` because `mid` itself was checked.
66perform_search(sorted_list, target, mid + 1, high)
67true ->
68# Target is in the left half, adjust high boundary.
69# The new high is `mid - 1` because `mid` itself was checked.
70perform_search(sorted_list, target, low, mid - 1)
71end
72else
73# If low > high, the search interval is empty, target not found.
74:not_found
75end
76end
77end
Algorithm description viewbox

Elixir: Implement Binary Search on Sorted List

Algorithm description:

This Elixir function implements an iterative binary search algorithm to find a target integer within a sorted list. It works by repeatedly dividing the search interval in half. If the target is less than the middle element, the search continues in the left half; otherwise, it continues in the right half. This process continues until the target is found or the interval becomes empty. Binary search is a fundamental algorithm used in various applications, including searching in databases, finding elements in sorted arrays, and implementing efficient lookup tables.

Algorithm explanation:

The `iterative_binary_search` function initializes the search boundaries `low` to 0 and `high` to the last index of the `sorted_list`. It then calls the `perform_search` helper function. The `perform_search` function iteratively checks if `low` is less than or equal to `high`. If it is, it calculates the `mid` index. The element at `mid` is compared to the `target`. If they match, the index `mid` is returned wrapped in `{:ok, mid}`. If the `middle_element` is less than the `target`, the search continues in the right half by recursively calling `perform_search` with `low` set to `mid + 1`. If the `middle_element` is greater than the `target`, the search continues in the left half by recursively calling `perform_search` with `high` set to `mid - 1`. If `low` becomes greater than `high`, it means the target is not present in the list, and `:not_found` is returned. The time complexity is O(log N) because the search space is halved in each step. The space complexity is O(1) for the iterative version, as it only uses a few variables to keep track of the search boundaries. Note that `Enum.at/2` on Elixir lists is O(N), making the effective complexity O(N log N) for lists. For true O(log N), one would use `Array` or `Vector` which offer O(1) element access.

Pseudocode:

FUNCTION iterative_binary_search(sorted_list, target):
  IF sorted_list is empty THEN
    RETURN "not_found"
  END IF

  SET low = 0
  SET high = length(sorted_list) - 1

  WHILE low <= high:
    SET mid = low + floor((high - low) / 2)
    SET middle_element = sorted_list[mid]

    IF middle_element == target THEN
      RETURN {"ok", mid}
    ELSE IF middle_element < target THEN
      SET low = mid + 1
    ELSE
      SET high = mid - 1
    END IF
  END WHILE

  RETURN "not_found"
END FUNCTION