Check to see if an array is already sorted?

前端 未结 8 1213
渐次进展
渐次进展 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:27

    For this to work efficiently you will want to sort during insertion. If you are dealing with unique items, a SortedSet is also an option.

    For clarification, if we patch array to allow for a sorted insertion, then we can keep the array in a sorted state:

    class Array
      def add_sorted(o)
        size = self.size
        if size == 0
          self << o
        elsif self.last < o
          self << o
        elsif self.first > o
          self.insert(0, o)
        else
          # This portion can be improved by using a binary search instead of linear
          self.each_with_index {|n, i| if n > o; self.insert(i, o); break; end}
        end
      end
    end
    
    a = []
    12.times{a.add_sorted(Random.rand(10))}
    p a # => [1, 1, 2, 2, 3, 4, 5, 5, 5, 5, 7]
    

    or to use the built in sort:

    class Array
      def add_sorted2(o)
        self << o
        self.sort
      end
    end
    

    or, if you are dealing with unique items:

    require "set"
    b = SortedSet.new
    12.times{b << Random.rand(10)}
    p b # => #
    

提交回复
热议问题