Thursday, August 29, 2013

Two way merging

Given two sorted lists, write a method that would perform the merging and
provide a new sorted list.

twowaymerge.rb

 <<-DOC
  Merge two sorted lists in ascending order (non-descending)
DOC
module Twowaymerge
  def merge (a,b)
    index_a = 0
    index_b = 0
    c=[]

    while (index_a < a.length and index_b < b.length) do
      if a[index_a] <= b[index_b] then
         c << a[index_a]
         index_a=index_a+1
      else
         c << b[index_b]
         index_b=index_b+1
      end
    end

    ## Stow away any remaining
    while index_b < b.length  do
      c << b[index_b]
      index_b=index_b+1
    end
    while index_a < a.length  do
      c << a[index_a]
      index_a=index_a+1
    end
  end
end

Testing:

irb -r ./twowaymerge.rb

irb(main):001:0> include Twowaymerge
=> Object
irb(main):002:0> a = [ 3, 5, 9]
=> [3, 5, 9]
irb(main):003:0> b = [ 1 ,2, 6]
=> [1, 2, 6]
irb(main):004:0> Twowaymerge.merge(a,b)
=> [1, 2, 3, 5, 6, 9]




No comments:

Post a Comment