LoginSignup
3
2

More than 5 years have passed since last update.

Rubyの配列がソート済みかどうかを調べる

Last updated at Posted at 2017-03-08

配列がソート済みかどうかを調べるコードです。(昇順)

module Enumerable
  def sorted?
    each_cons(2).all? {|a, b| a <= b }
  end

  def sorted_by?
    each_cons(2).all? {|a, b| yield(a) <= yield(b) }
  end
end

p [3,2,1].sorted? #=> false
p [1,2,3].sorted? #=> true

p ['1','2','13'].sorted?            #=> false
p ['1','2','13'].sorted_by?(&:to_i) #=> true

each_cons で要素を2つずつ取り出し <= を使って値の比較を行っています。比較を行った結果が全て true なら昇順で並んでいます。降順で並んでいるかどうかを確かめるときには >= を使用します。

追記

@scivola さんのコメントを元に修正を行いました。ありがとうございます :pray:

使い道

ボゴソート

class Array
  def bogosort!
    shuffle! until sorted?
    self
  end
end

p [*1..5].shuffle.bogosort! #=> [1, 2, 3, 4, 5]

bsearch 前のチェック

ary = [0, 4, 7, 10, 12].shuffle
ary.sort! unless ary.sorted?
p ary.bsearch {|x| x >= 4 } # => 4

etc...

参考サイト

https://docs.ruby-lang.org/ja/latest/class/Array.html
https://docs.ruby-lang.org/ja/latest/class/Enumerator.html

3
2
2

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
3
2