Check to see if an array is already sorted?

前端 未结 8 1209
渐次进展
渐次进展 2020-12-17 08:52

I know how to put an array in order, but in this case I just want to see if it is in order. An array of strings would be the easiest, I imagine, and answer

8条回答
  •  Happy的楠姐
    2020-12-17 09:31

    reduce can compare each element to the one before, and stop when it finds one out of order:

    array.reduce{|prev,l| break unless l[0] >= prev[0]; l}
    

提交回复
热议问题