From 7b8d784040f1fd88fce2658b704b300f7421c885 Mon Sep 17 00:00:00 2001 From: "Yukihiro \"Matz\" Matsumoto" Date: Tue, 25 Jul 2017 14:42:38 +0900 Subject: Reimplement sort method to reduce array copying. --- mrblib/enum.rb | 46 +--------------------------------------------- 1 file changed, 1 insertion(+), 45 deletions(-) (limited to 'mrblib/enum.rb') diff --git a/mrblib/enum.rb b/mrblib/enum.rb index fb55efcf8..12bd1d37b 100644 --- a/mrblib/enum.rb +++ b/mrblib/enum.rb @@ -315,45 +315,6 @@ module Enumerable # ISO 15.3.2.2.18 alias select find_all - ## - # TODO - # Does this OK? Please test it. - def __sort_sub__(sorted, work, src_ary, head, tail, &block) - if head == tail - sorted[head] = work[head] if src_ary == 1 - return - end - - # on current step, which is a src ary? - if src_ary == 0 - src, dst = sorted, work - else - src, dst = work, sorted - end - - key = src[head] # key value for dividing values - i, j = head, tail # position to store on the dst ary - - (head + 1).upto(tail){|idx| - if ((block)? block.call(src[idx], key): (src[idx] <=> key)) > 0 - # larger than key - dst[j] = src[idx] - j -= 1 - else - dst[i] = src[idx] - i += 1 - end - } - - sorted[i] = key - - # sort each sub-array - src_ary = (src_ary + 1) % 2 # exchange a src ary - __sort_sub__(sorted, work, src_ary, head, i - 1, &block) if i > head - __sort_sub__(sorted, work, src_ary, i + 1, tail, &block) if i < tail - end -# private :__sort_sub__ - ## # Return a sorted array of all elements # which are yield by +each+. If no block @@ -364,12 +325,7 @@ module Enumerable # # ISO 15.3.2.2.19 def sort(&block) - ary = [] - self.each{|*val| ary.push(val.__svalue)} - if ary.size > 1 - __sort_sub__(ary, ::Array.new(ary.size), 0, 0, ary.size - 1, &block) - end - ary + self.map{|*val| val.__svalue}.sort end ## -- cgit v1.2.3