Check to see if an array is already sorted?

前端 未结 8 1108
渐次进展
渐次进展 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条回答
  • 2020-12-17 09:36
    def ascending? (array)
        yes = true
        array.reduce { |l, r| break unless yes &= (l[0] <= r[0]); l }
        yes
    end
    
    
    def descending? (array)
        yes = true
        array.reduce { |l, r| break unless yes &= (l[0] >= r[0]); l }
        yes
    end
    
    0 讨论(0)
  • 2020-12-17 09:37

    If it turns out the array isn't sorted, will your next action always be to sort it? For that use case (though of course depending on the number of times the array will already be sorted), you may not want to check whether it is sorted, but instead simply choose to always sort the array. Sorting an already sorted array is pretty efficient with many algorithms and merely checking whether an array is already sorted is not much less work, making checking + sorting more work than simply always sorting.

    0 讨论(0)
提交回复
热议问题