Last active
December 14, 2016 08:14
-
-
Save dhalai/7f868b55910683ecc4454c5c58cc596b to your computer and use it in GitHub Desktop.
Algorithm optimization to avoid O(n^2). Fixed version of https://medium.com/@sashang/no-debugging-programming-in-elixir-e26f3d3fd243
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Inversion do | |
def run(filename) do | |
{sorted, count} = File.read!(filename) | |
|> String.split("\r\n", trim: true) | |
|> Enum.map(fn(x) -> String.to_integer(x) end) | |
|> devide_and_conquer | |
count | |
end | |
defp devide_and_conquer(data) do | |
case data do | |
[] -> {[], 0} | |
[x] -> {[x], 0} | |
[x,y] when x > y -> {[y,x], 1} | |
[x,y] when x <= y -> {[x,y], 0} | |
list -> | |
count = length(list) | |
half_index = div(count, 2) | |
{sorted_x, x} = devide_and_conquer(Enum.slice(list, (0..half_index-1))) | |
{sorted_y, y} = devide_and_conquer(Enum.slice(list, half_index..count-1)) | |
{sorted_z, z} = merge(sorted_x, sorted_y, [], 0) | |
{Enum.reverse(sorted_z), x + y + z} | |
end | |
end | |
defp merge(a, b, acc_list, acc_inversions) do | |
case {a, b} do | |
{[], []} -> {acc_list, acc_inversions} | |
{a, []} -> {Enum.reverse(a) ++ acc_list, acc_inversions} | |
{[], b} -> {Enum.reverse(b) ++ acc_list, acc_inversions} | |
{a, b} when hd(a) > hd(b) -> merge(a, tl(b), [hd(b) | acc_list], length(a) + acc_inversions) | |
{a, b} when hd(a) <= hd(b) -> merge(tl(a), b, [hd(a) | acc_list], acc_inversions) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment