-4

Sort the elements of two sorted arrays without using .sort method and put the sorted elements in a new array in RUBY

I have two arrays, like this:

a = [1,4,6,9]
b = [2,5,7,8]

and my output should be:

c = [1,2,4,5,6,7,8,9]

How do I do this?

1
  • Please add what you have tried and at what point you need specific help. Otherwise it smells a lot like homework. Commented Jul 1, 2015 at 8:14

2 Answers 2

0

Here is a function that will help you do what you want.

def my_sort_function(a,b)
  n = a.length + b.length
  if a.length < b.length
    min = a.length
  else
    min = b.length
  end
  c=[]

    min.times do |i|
      if a[i] > b[i]
        c << b[i]
        c  << a[i]
      else
        c << a[i]
        c  << b[i]
        end
    end
  if min == a.length

    (c << b[(min)..(b.length-1)]).flatten!

  else
    (c << a[(min)..(a.length-1)]).flatten!

  end

  loop do
    swapped = false

    (n-1).times do |i|
      if c[i] > c[i+1]
        c[i], c[i+1] = c[i+1], c[i]
        swapped = true
      end
    end

    break if not swapped
  end
  c
end

a = [1,4,6]
b = [2,5,7,8]

puts a    #=> a:[1,4,6]
puts b    #=> b:[2,5,7,8]

c= my_sort_function(a,b)
puts c    #=> c:[1,2,4,5,6,7,8]
puts "sorting Done!"
Sign up to request clarification or add additional context in comments.

11 Comments

But i want to compare the elements of two arrays first and later add them to a new array like
a = {1,4,6,9} b = {8,5,2,7} if a[i] > b[i] push c[i] = b[i] push c[i+1] = a[i] else if b[i] > a[i] push c[i] = a[i] push c[i+1] = b[i]
But in your question you are saying that the two arrays are sorted, you may want to edit the question
consider my both arrays a & b are sorted arrays
like a = {1,4,6,9} and b = {2,5,7,8}
|
0

You cerainly want to make use of the fact that the two arrays to be merged are already sorted. This is one way to do that:

def merge_sort(a,b)
  ac, bc = a.dup, b.dup
  (a.size+b.size).times.each_with_object([]) do |_,c|
    c <<
      case [ac.any?, bc.any?]
      when [true,true]  then (ac.first <= bc.first) ? ac.shift : bc.shift
      when [true,false] then ac.shift
      else                   bc.shift
      end
   end
 end

 a = [1,4,6,9]
 b = [2,5,7,8]    

 c = merge_sort a,b 
   #=> [1,2,4,5,6,7,8,9] 

The first line is to avoid mutating (changing) a or b.

2 Comments

Thank you so much but i want to store it in a new array
I'm not sure I understand what you mean, but I've edited to use the three variable names in your question: a, b and c.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.