LoginSignup
4
1

More than 3 years have passed since last update.

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

Last updated at Posted at 2019-07-30

今話題のスターリンソート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"]

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

引用元

4
1
1

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
  3. You can use dark theme
What you can do with signing up
4
1