🍣
Ruby のパターンマッチを利用したクイックソート
書いてみたもののあんまりパターンマッチ感はない。
module SortableArray
refine Array do
def quick_sort
case self
in [x, *xs]
xs.partition { _1 < x }.then { [*_1.quick_sort, x, *_2.quick_sort] }
in []
[]
end
end
end
end
using SortableArray
pp [0, 9, 2, 10, 5, 1, 4, 6, 3, 8, 7].quick_sort
# => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
pp [0].quick_sort
# => [0]
もうちょいいい感じにかけないかなー。
Discussion