# frozen_string_literal: true class Array # Returns a new array created by sorting +self+, using quicksort algorithm. # # Comparisons for the sort will be done using the <=> operator or using an optional code block. # # The block must implement a comparison between +a+ and +b+ and return an integer less than 0 when +b+ follows +a+, # +0+ when +a+ and +b+ are equivalent, or an integer greater than 0 when +a+ follows +b+. # # The result is not guaranteed to be stable. When the comparison of two elements returns +0+, the order of the # elements is unpredictable. # # @return [Array] the sorted array def quick_sort(&block) return dup if length <= 1 left, right = self[1..-1].partition { |y| sort_compare(first, y, &block).positive? } left.quick_sort + [first] + right.quick_sort end # Sorts +self+ in place, using quicksort algorithm. # # Comparisons for the sort will be done using the <=> operator or using an optional code block. # # The block must implement a comparison between +a+ and +b+ and return an integer less than 0 when +b+ follows +a+, # +0+ when +a+ and +b+ are equivalent, or an integer greater than 0 when +a+ follows +b+. # # The result is not guaranteed to be stable. When the comparison of two elements returns +0+, the order of the # elements is unpredictable. # # @return [Array] +self+ def quick_sort!(&block) become_clone_of quick_sort(&block) end # Returns a new array created by sorting +self+ with quicksort algorithm, using a set of keys generated by mapping # the values in self through the given block. # # The result is not guaranteed to be stable. When the comparison of two elements returns +0+, the order of the # elements is unpredictable. # # If no block is given, an Enumerator is returned instead. # # @return [Array] if a block is given, the sorted array # @return [Enumerator] if no block is given, an Enumerator def quick_sort_by(&_block) if block_given? quick_sort do |a, b| yield(a) <=> yield(b) end else to_enum :quick_sort_by end end # Sorts +self+ in place with quicksort algorithm, using a set of keys generated by mapping the values in self through # the given block. # # The result is not guaranteed to be stable. When the comparison of two elements returns +0+, the order of the # elements is unpredictable. # # If no block is given, an Enumerator is returned instead. # # @return [Array] if a block is given, the sorted array # @return [Enumerator] if no block is given, an Enumerator def quick_sort_by!(&block) if block_given? become_clone_of quick_sort_by(&block) else to_enum :quick_sort_by! end end end