The impressive imperative process of merging the two ...
a = [1,3,7,11] b = [2,4,6,14] c = merge_sorted_arrays(a,b) def merge_sorted_arrays(a,b) a.reverse! b.reverse! output = [] loop do break if a.empty? || b.empty? output << (a.last < b.last ? a.pop : b.pop) end return output + a.reverse + b.reverse end
Perhaps the use of .slice! taking the first element is better than reversing and popping up?
======================
edited after the fourth comment:
That's right ... I had a different game, but I need to do real work or they will fire me; -)
In a large array of integers, my original method is faster than using sort_by, but after filling in the arrays of 100,000 OpenStruct objects and sorting by the sort_by attribute, it was 100 times faster.
Here are my benchmarking results:
def pop_merge_sorted_arrays(array1,array2) array1.reverse! array2.reverse! output = [] loop do break if array1.empty? || array2.empty? output << (array1.last.my_field < array2.last.my_field ? array1.pop : array2.pop) end return output + array1.reverse + array2.reverse end def shift_merge_sorted_arrays(array1,array2) output = [] loop do break if array1.empty? || array2.empty? output << (array1.first.my_field < array2.first.my_field ? array1.shift : array2.shift) end return output + array1 + array2 end def slice_merge_sorted_arrays(array1,array2) output = [] loop do break if array1.empty? || array2.empty? output << (array1.first.my_field < array2.first.my_field ? array1.slice!(0) : array2.slice!(0)) end return output + array1 + array2 end a=(1..100000).map{|x|OpenStruct.new(:my_field => rand)}.sort_by(:my_field) b=(1..100000).map{|x|OpenStruct.new(:my_field => rand)}.sort_by(:my_field)
Thus, it seems that you can write a method that will shuffle them, while preserving the order, which will be pretty fast (and there are probably a few more advantages to squeezing the shift_merge method, but it really doesnβt have to be worth it just combine them together and use sort_by for convenience? :-)
I hope this is not considered a retreat ...