验证数组是按升序还是降序排列

时间:2012-10-15 16:49:43

标签: ruby arrays

我有一个包含日期的数组。

dates = [#<DateTime: 2002-07-01T00:00:00+00:00 ((2452457j,0s,0n),+0s,2299161j)>, #<DateTime: 2003-10-31T00:00:00+00:00 ((2452944j,0s,0n),+0s,2299161j)>, #<DateTime: 2003-12-01T00:00:00+00:00 ((2452975j,0s,0n),+0s,2299161j)>, #<DateTime: 2004-03-01T00:00:00+00:00 ((2453066j,0s,0n),+0s,2299161j)>, #<DateTime: 2004-03-01T00:00:00+00:00 ((2453066j,0s,0n),+0s,2299161j)>]

如果该数组的升序或降序,我如何检查该数组的排序顺序?

4 个答案:

答案 0 :(得分:9)

如果每两个相邻元素中的第一个元素小于或等于第二个元素,则数组呈上升趋势:

def ascending? arr
  arr.each_cons(2).all?{|left, right| left <= right}
end

或者(更漂亮但不幸的是更慢),您可以将数组与其自身的排序版本进行比较:

def ascending? arr
  arr == arr.sort
end

答案 1 :(得分:6)

以下是处理速度的一些基准测试结果:

require 'benchmark'
require 'date'

ary = (DateTime.parse('2002-07-01T00:00:00+00:00') .. DateTime.parse('2004-03-01T00:00:00+00:00')).to_a

def ascending1? arr
  arr.reduce{ |e1,e2| e1 <= e2 ? e2 : (return false) }; true
end

def ascending2? arr
  arr.each_cons(2).all?{|i,j| i <= j}
end

def ascending3? arr
  arr == arr.sort
end

n = 10_000
Benchmark.bm(9) do |b|
  b.report('reduce')    { n.times{ ascending1?(ary) } }
  b.report('each_cons') { n.times{ ascending2?(ary) } }
  b.report('sort')      { n.times{ ascending3?(ary) } }
end

测试结果:

                user     system      total        real
reduce      1.380000   0.000000   1.380000 (  1.381107)
each_cons   2.250000   0.000000   2.250000 (  2.243958)
sort        0.670000   0.000000   0.670000 (  0.675025)

答案 2 :(得分:4)

为什么不检查排序的数组是否与未排序的数组相同?

提升

array == array.sort

array == array.sort.reverse降序

答案 3 :(得分:0)

我认为reduce会比each_cons

更快
def ascending? arr
  arr.reduce{ |e1,e2| e1 <= e2 ? e2 : (return false) }; true
end