LoginSignup
1

More than 3 years have passed since last update.

posted at

updated at

rubyでスターリンソートをやってみた(ブロック渡しも可能)

今話題のスターリンソートruby で実装してみました。

準備

stalin_sort.rb
class Array
  # Githubの実装と同様
  def stalin_sort
    return [] if empty?

    max = first
    select do |x|
      next if max > x

      max = x
      x
    end
  end

  # ブロックあり
  def stalin_sort_by(&block)
    return [] if empty?

    max = yield(first)
    map { |x| [yield(x), x] }
      .select { |y, _x| next if max > y; max = y }
      .map    { |_y, x| x }
  end
end

Githubの実装Array を引数に取り実行していますが、 ruby の良さを活かすためクラス拡張に変更しました。

実行

[1, 2, 1, 1, 4, 3, 9].stalin_sort
# => [1, 2, 4, 9]

names = %w(alice bob ava benjamin carol)

# ブロックなし
names.stalin_sort
# => ["alice", "bob", "carol"]

# ブロックあり
names.stalin_sort_by(&:length)
# => ["alice", "benjamin"]

簡単になりますが以上です。
掲載したものより良いコードがあれば是非ともお願いします!

引用元

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
1