Skip to content

Instantly share code, notes, and snippets.

@ryuta-ito
Last active January 7, 2017 23:53
Show Gist options
  • Save ryuta-ito/5d072329a0fcd03a576f43e7bab82fb4 to your computer and use it in GitHub Desktop.
Save ryuta-ito/5d072329a0fcd03a576f43e7bab82fb4 to your computer and use it in GitHub Desktop.
defmodule Sort do
import List
import Enum
def bubble_sort([]), do: []
def bubble_sort(list), do: bubble_sort_(bubble(list))
def bubble_sort_([]), do: []
def bubble_sort_(list), do: bubble_sort(take(list, length(list)-1)) ++ [last list]
def bubble([]), do: []
def bubble([x]), do: [x]
def bubble([x, y]), do: if x < y, do: [x, y], else: [y, x]
def bubble([x | [y | tail]]) do
if x < y, do: [x] ++ bubble([y] ++ tail), else: [y] ++ bubble([x] ++ tail)
end
end
list = Enum.take_random(Enum.to_list(1..50), 50)
IO.inspect Sort.bubble_sort list
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment