|
| 1 | +defmodule SelectionSort do |
| 2 | + def sort(list), do: do_sort(list, []) |
| 3 | + |
| 4 | + defp do_sort([], acc), do: Enum.reverse(acc) |
| 5 | + |
| 6 | + defp do_sort(list, acc) do |
| 7 | + smallest_index = find_smallest_index(list, 0, nil, nil) |
| 8 | + {smallest_value, list_rest} = List.pop_at(list, smallest_index) |
| 9 | + do_sort(list_rest, [smallest_value | acc]) |
| 10 | + end |
| 11 | + |
| 12 | + defguardp new_smallest_value?(value, min_value) when is_nil(min_value) or value < min_value |
| 13 | + |
| 14 | + defp find_smallest_index([], _, _, min_index), do: min_index |
| 15 | + |
| 16 | + defp find_smallest_index([head | tail], index, min_value, _) |
| 17 | + when new_smallest_value?(head, min_value), |
| 18 | + do: find_smallest_index(tail, index + 1, head, index) |
| 19 | + |
| 20 | + defp find_smallest_index([_ | tail], index, min_value, min_index), |
| 21 | + do: find_smallest_index(tail, index + 1, min_value, min_index) |
| 22 | +end |
| 23 | + |
| 24 | +IO.inspect(SelectionSort.sort([5, 3, 6, 2, 10])) |
0 commit comments