defmodule Algorithms.CodeWars.SortTheOdd do
@moduledoc """
line 30: Theta(n)
line 31: BigO(n log n)
line 32: Theta(n + m) - where n: input List length, m: number of odd in input List
line 33: BigO(1) - note: only for List
-----------------------------
Complexity: BigO(n log n)
"""
require Integer
@doc """
take a List and return the list with only odd numbers ordered
"""
@spec sort_the_odd(list(integer)) :: list(integer)
def sort_the_odd(input_list) do
input_list
|> Enum.filter(fn el -> Integer.is_odd(el) end)
|> Enum.sort()
|> merge(input_list, [])
|> Enum.reverse()
end
@doc """
recursive function: take sorted odd List, input List, result
return the merged list with the even number fixed at the same index
"""
@spec merge(list(integer), list(integer), list(integer)) :: list(integer)
def merge([], input_list, result), do: Enum.reverse(input_list) |> Enum.concat(result)
def merge(sorted_list, [], result), do: Enum.concat(sorted_list, result)
def merge([sorted_head | sorted_rest], [head | rest], result) do
case Integer.is_odd(head) do
true -> merge(sorted_rest, rest, [sorted_head | result])
false -> merge([sorted_head | sorted_rest], rest, [head | result])
end
end
end