fork download
  1. defmodule LinearSearch do
  2. @doc """
  3. Линейный поиск в списке — возвращает индекс или nil.
  4. """
  5. def search(list, target) do
  6. search_with_index(list, target, 0)
  7. end
  8.  
  9. defp search_with_index([], _target, _index), do: nil
  10.  
  11. defp search_with_index([head | tail], target, index) do
  12. if head == target do
  13. index
  14. else
  15. search_with_index(tail, target, index + 1)
  16. end
  17. end
  18. end
  19.  
  20. # Пример использования
  21. arr = [12, 1456, 53, 12451, 992, 81, 666]
  22. target = 992
  23.  
  24. case LinearSearch.search(arr, target) do
  25. nil ->
  26. IO.puts("The #{target} element was not found")
  27.  
  28. index ->
  29. IO.puts("The #{target} element was found at position #{index}")
  30. end
Success #stdin #stdout 0.53s 42368KB
stdin
Standard input is empty
stdout
The 992 element was found at position 4